我有一个带导航栏的树枝模板,所有其他模板(页面)都包含此模板。我有一个值应该等于所有页面。如何设置此值?
我在控制器中尝试这样的事情:
public function setNotificationsAction() {
$this->setNotifications();
return $this->render('AcmeMyBundle::navbar.html.twig', array(
'debts' => $this->notifications,
));
}
然后在模板中:
<span class="badge badge-important">
{% render(controller('AcmeMyBundle:DebtsLoansController:setNotifications')) %}
{{ debts }}
</span>
结果我想要这样:
<span class="badge badge-important">
3
</span>
但数字应该不同,控制器应该告诉它。
我还尝试创建一个函数,它返回值并以上面的方式调用它。
我也尝试了这种语法
{{ render(controller('AcmeMyBundle:DebtsLoansController:setNotifications')) }}
但它也不起作用。
我得到以下错误:
The function "controller" does not exist in AcmeMyBundle::navbar.html.twig at line 6
你知道如何实现这一目标而不必编辑每个控制器和每个模板:S非常感谢!
答案 0 :(得分:3)
好吧,我建议你创建自己的Twig扩展。有些东西:
<span class="badge">
{{ acme_notifications() }}
</span>
namespace Acme\DemoBundle\Twig\AcmeDemoExtension
class AcmeDemoExtension extends \Twig_Extension
{
public function getFunctions()
{
return array(
'acme_notifications' => new \Twig_Function_Method($this, 'getNotifications');
);
}
public function getNotifications()
{
$notifications = ...;
return $notifications;
}
}
详细了解如何在the Symfony2 documentation中创建自己的Twig扩展程序。
答案 1 :(得分:2)
您不需要控制器部分:
{% render "AcmeBundle:MyController:MyAction" %}
请注意,render
是一个完整的新请求,贯穿整个Symfony生命周期,因此如果您滥用它会影响性能。
编辑:正如@Wouter J所指出的那样:在Symfony 2.2之前使用上面的表示法。在Symfony 2.2之后,必须使用以下内容:
{{ render(controller('AcmeArticleBundle:Article:recentArticles', { 'max': 3 })) }}