我有一个带有导航栏的 Twig 模板,所有其他模板(页面)都包含此模板。我其中有一个值应该等于所有页面。如何设置这个值?
我在 Controller 中尝试这样的事情:
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>
但是数字应该不同并且 Controller 应该告诉它。
我还尝试创建一个返回值的函数并按照上面的方式调用它。
我也尝试过这种语法
{{ render(controller('AcmeMyBundle:DebtsLoansController:setNotifications')) }}
但它也不起作用。
我收到以下错误:
AcmeMyBundle::navbar.html.twig 第 6 行中不存在“controller”函数
您是否知道如何实现这一目标,并且不必编辑每个 Controller 和每个模板:S 提前非常感谢!
最佳答案
好吧,我建议创建您自己的 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 扩展的更多信息.
关于symfony - 使 Controller 只给模板一个值,而不渲染它 - Symfony2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17209163/