2013-11-25 207 views
1

我有一個變量假設是: $ menustr;此變量包含代碼HTML和例如一些枝條部分:在樹枝模板上打印一個包含html和樹枝的變量

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

我需要,瀏覽器採取的代碼html和嫩枝的一部分,在這種魔門是 「{{路徑(~~~~~ )}}「

我做了一個返回,我發送名爲」$ menustr「的變量,並且在爲html代碼使用expresion」raw「之後,但是這並沒有使枝條代碼生效。

這是TE回報:

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

,這裏是模板內容:

{{ menu | raw }} 
+0

爲什麼你混合樹枝和PHP模板?你應該去與其中之一。 – ferdynator

回答

2

枝條無法呈現含有樹枝串。在Twig 1.中沒有像eval的功能。

你可以做的是將路徑邏輯移動到PHP的東西。 router服務可以生成url,就像枝條函數的path一樣。如果你是在繼承基礎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

0

入住這束:https://github.com/LaKrue/TwigstringBundle 這包增加了渲染的字符串,而不是與Symfony2的原生枝條模板引擎文件的可能性:

$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) 
));