我正在使用Symfony2和Twig.我的控制器中有一个函数(下面),它返回一个特定的文本.是否可以直接从我的模板调用该函数并将模板中的{{text}}更改为函数返回的任何内容,可能是通过Ajax?
这是我的功能:
public function generateCode($url) {
$url = $_SERVER['SERVER_NAME'] . '/embed/' . $url;
$return = '<iframe>'.$url.'</iframe>';
return $return;
}
Run Code Online (Sandbox Code Playgroud)
另一个控制器函数调用上面的函数并呈现我的模板:
public function getCodeAction($url) {
$text = $this->generateCode($url);
return $this->render('MyMyBundle:User:code.html.twig', array('text' => $text));
}
Run Code Online (Sandbox Code Playgroud)
在我使用的模板中:
{{ text }}
Run Code Online (Sandbox Code Playgroud)
显示值.
Dan*_*ows 36
在Symfony 2.2中,这已经改变了.
渲染标记签名和参数已更改.
之前:
{% render 'BlogBundle:Post:list' with { 'limit': 2 }, { 'alt': BlogBundle:Post:error' } %}后:
{% render controller('BlogBundle:Post:list', { 'limit': 2 }), { 'alt': 'BlogBundle:Post:error' } %}要么
{{ render(controller('BlogBundle:Post:list', { 'limit': 2 }), { 'alt': 'BlogBundle:Post:error'}) }}注意:该功能是首选方式.
请参阅https://github.com/symfony/symfony/blob/2.2/UPGRADE-2.2.md
小智 23
如果你有动态数据,你可以使用ajax,但是从我的简要信息中我可以看到,你总是可以直接从你的视图中执行该控制器功能:
{% render "MyMyBundle:User:generateCode" with { 'url': 'your url here' } %}
Run Code Online (Sandbox Code Playgroud)
有关此内容的更多信息,请访问:http: //symfony.com/doc/2.0/quick_tour/the_view.html,嵌入其他控制器
为了记录,在新版本中,您需要使用绝对URL:
{{ render url('my_route_id', {'param': value}) }}
Run Code Online (Sandbox Code Playgroud)