如何使用 Symfony2 加载控制器功能并将其呈现在树枝标签中? [英] How to load a controller function and render it in a twig tag using Symfony2?
问题描述
我正在使用 Symfony2 和 Twig.我的控制器中有一个返回特定文本的函数(如下).是否可以直接从我的模板中调用该函数并将模板中的 {{text}} 更改为函数返回的任何内容,可能是通过 Ajax?
I am using Symfony2 and Twig. I have a function (below) in my controller that returns a specific text. Is it possible to call that function directly from my template and change the {{text}} in my template to whatever the function returns, possibly via Ajax?
这是我的功能:
public function generateCode($url) {
$url = $_SERVER['SERVER_NAME'] . '/embed/' . $url;
$return = '<iframe>'.$url.'</iframe>';
return $return;
}
另一个控制器函数调用上面的函数并呈现我的模板:
Another controller function calls the function above and renders my template:
public function getCodeAction($url) {
$text = $this->generateCode($url);
return $this->render('MyMyBundle:User:code.html.twig', array('text' => $text));
}
在我的模板中我使用:
{{ text }}
显示值.
推荐答案
如果你有动态数据,你可以使用 ajax,但据我从你的简要信息中看到,你总是可以直接从你的视图中执行该控制器函数:
You can use ajax if you have dynamic data, but as far as I can see from your brief info, you can always execute that controller function directly from your view:
{% render "MyMyBundle:User:generateCode" with { 'url': 'your url here' } %}
有关此的更多信息,请访问:http://symfony.com/doc/2.0/quick_tour/the_view.html, 在嵌入其他控制器下
More Information on this available at: http://symfony.com/doc/2.0/quick_tour/the_view.html, under Embedding other Controllers
这篇关于如何使用 Symfony2 加载控制器功能并将其呈现在树枝标签中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!