phptwigfuelphpredbean

Access redbeanphp object property with twig


This could be a simple problem but is messing my head out.

The thing is I'm doing a project with fuelPHP, RedBean and Twig. All seems to work fine and I'm progressing really well with this framework.

The problem I encounter which I've not find any solution yet is that Twig it's not able to access {{object.property}} if I get the object from redbean. Which is totally strange because if I use my own MVC framework the exact same code (Twig+Redbean also) works.

For example

public function action_messages() {
    $room = \Uri::segment(3);
    $this->data['messages'] = \R::find('message', 'room = ? ORDER BY id', array($room));
    
    // This is working because it's converting each row to array
    /*foreach($this->data['messages'] as $id => $message)
        $this->data['messages'][$id] = $message->export();*/
    
    return \Response::forge(\View::forge('chat/messages.twig', $this->data));
}

The thing works as expected if I get the export as an array but not as an object.

{%for message in messages%}
     <b>{{message.user.id}}</b>{{message.datetime}}: {{message.text}}
{%endfor%}

I'm really lost with this. So I would appreciate any possible help.

Edit: (More info)

If I put

{%for message in messages%}
{{message}}<br/>
{%endfor%}

I get this output from the Var.

{"id":"23","text":"A test","room":"1","datetime":"2012-10-05 15:32:36","user_id":"1"}

Solution

  • Finally I got it working.

    The problem was in the Twig config in the FuelPHP framework.

    The auto_encode parameter does the conversion of json to array in case of object properties. So you MUST set it to false (It's true by default).

    Adjust your config to get something like this.

    // TWIG ( http://www.twig-project.org/documentation )
    // ------------------------------------------------------------------------
    'View_Twig' => array(
        'include' => APPPATH.'vendor'.DS.'Twig'.DS.'Autoloader.php',
        'auto_encode' => false, // Remember to set this to false
        'views_paths' => array(APPPATH.'views'),
        'delimiters' => array(
            'tag_block'     => array('left' => '{%', 'right' => '%}'),
            'tag_comment'   => array('left' => '{#', 'right' => '#}'),
            'tag_variable'  => array('left' => '{{', 'right' => '}}'),
        ),
        'environment' => array(
            'debug'                => false,
            'charset'              => 'utf-8',
            'base_template_class'  => 'Twig_Template',
            'cache'                => APPPATH.'cache'.DS.'twig'.DS,
            'auto_reload'          => true,
            'strict_variables'     => false,
            'autoescape'           => false,
            'optimizations'        => -1,
        ),
        'extensions' => array(
            'Twig_Fuel_Extension'
        ),
    ),
    

    And it will work like a charm :)