我有一个变量,假设它是:$menustr;该变量包含代码html和一些分支部分,例如:
$menustr .= '<li><a href="{{ path("'. $actual['direccion'] .'") }}" >'. $actual['nombre'] .'</a></li>';
我需要浏览器获取代码html和此时为"{{path(~~~~~)}}"
我会返回一个名为"$menustr"的变量,然后对html代码使用表达式"raw",但这不会使trick代码生效。
这是返回:
return $this->render('::menu.html.twig', array('menu' => $menustr));
这是模板内容:
{{ menu | raw }}
Twig无法渲染包含Twig的字符串。在Twig1中没有类似eval
函数的东西。
您可以做的是将路径逻辑移动到PHP中。router
服务可以生成url,就像path
trich函数一样。如果你在一个扩展基本Controller
的控制器中,你可以简单地使用generateUrl
:
$menuString .= '<li><a href="'.$this->generateUrl($actual['direction'].'">'. $actual['nombre'] .'</a></li>';
return $this->render('::menu.html.twig', array(
'menu' => $menuString,
));
此外,当在Symfony中使用菜单时,我建议您查看KnpMenuBundle。
编辑:1。正如@PepaMartinec所指出的,有一个函数可以做到这一点,它被称为template_from_string
您可以使用template_from_string
函数渲染存储在变量中的Twig模板。
检查此捆绑包:https://github.com/LaKrue/TwigstringBundle该捆绑包增加了使用Symfony2原生Twig模板引擎呈现字符串而不是文件的可能性:
$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
在你的情况下,我会是:
return $this->render('::menu.html.twig', array(
'menu' => $this->get('twigstring')->render($menustr, $vars)
));