BigJ BigJ - 1 month ago 11
PHP Question

Render Mustache PHP template with Doctrine entity model

In my Symfony controller I want to render a Mustache PHP template, with a Doctrine entity:

// The Doctrine entity, a dump($user) shows the correct entity
$user = $this->get('x_service')->getUserById($id);

$templateFile = file_get_contents('.../path/to/file'); // tested, it works
$mustache = new \Mustache_Engine();
$renderedTemplate = $mustache->render($templateFile, array('user' => $user));


The template file looks like this:

<p>
User name: {{ user.name }}
</p>


But the variable is not put into the template. It only shows the "User name:" string. I also tried without the associative array:

$renderedTemplate = $mustache->render($templateFile, $user);

// the template file:

<p>
User name: {{ name }}
</p>


This did not work either.

However, when I put another variable with the associative array, that does shows:

$renderedTemplate = $mustache->render($templateFile, array('user' => $user, 'meh' => 'hem'));

// the template file:

<p>
User name: {{ name }} <- still no output
Meh: {{ meh }} <- this does give output
</p>


Some more information: I just want to render this small mustache template in my controller. For the controller response I'm using Twig. This is because I'm just reusing a front-end Mustache.js template.

Edit

As I read the manual, it should work to give an object in the model:

enter image description here

Answer Source

It won't work if your user properties are not public.

Try {{ user.getName }}