2

I have a variable suppose that is: $menustr; this variable contains code html and some twig parts for example:

$menustr .= '<li><a href="{{ path("'. $actual['direccion']  .'") }}" >'. $actual['nombre'] .'</a></li>';

I need that the browser take the code html and the part of twig that in this momen is the "{{ path(~~~~~) }}"

I make a return where i send the variable called "$menustr" and after use the expresion "raw" for the html code but this dont make effective the twig code.

This is te return:

return $this->render('::menu.html.twig', array('menu' => $menustr));

and here is the template content:

{{ menu | raw }}
1
  • Why do you mix twig and php templates? Your should go with one of them. Commented Nov 25, 2013 at 17:39

3 Answers 3

2

Twig can't render strings containing twig. There is not something like an eval function in Twig1..

What you can do is moving the path logic to the PHP stuff. The router service can generate urls, just like the path twig function does. If you are in a controller which extends the base Controller, you can simply use generateUrl:

$menuString .= '<li><a href="'.$this->generateUrl($actual['direction'].'">'. $actual['nombre'] .'</a></li>';

return $this->render('::menu.html.twig', array(
    'menu' => $menuString,
));

Also, when using menu's in Symfony, I recommend to take a look at the KnpMenuBundle.


EDIT: 1. As pointed by @PepaMartinec there is a function which can do this and it is called template_from_string

Sign up to request clarification or add additional context in comments.

Comments

2

You can render Twig template stored in a varible using the template_from_string function.

Comments

0

Check this bundle: https://github.com/LaKrue/TwigstringBundle This Bundle adds the possibility to render strings instead of files with the Symfony2 native Twig templating engine:

$vars = array('var'=>'x');
// render example string
$vars['test'] = $this->get('twigstring')->render('v {{ var }} {% if var is defined %} y {% endif %} z', $vars);
// output
v x y z

In your case i would be:

return $this->render('::menu.html.twig', array(
    'menu' => $this->get('twigstring')->render($menustr, $vars)
));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.