在 Symfony 2 中分配全局 Twig 变量? [英] Assign a global Twig variable in Symfony 2?
问题描述
我的 Web 应用程序作为顶部栏,我需要在其中显示未读消息的数量.每个 User
实体都与 Message
(多对多)关联.显示消息总数(对于给定用户)很简单:
My web application as a topbar where i need to display the number of unreaded messages. Each User
entity as an association with Message
(many-to-many). Showing the total number of messages (for a given user) would be simple:
class User
{
/*
* @ORM\ManyToMany(targetEntity="Message", invertedBy="users")
*/
private $messages;
}
在树枝中:
Total messages: {{ app.user.messages|length }}.
但是如果我需要只计算新消息怎么办?假设我的存储库有一个 getNewMessages(User $user)
方法,如何全局分配此值以在每个模板中使用?
But what if i need to count only new messages? Assuming my repository has a getNewMessages(User $user)
method, how can assign this value globally to use in every template?
我知道 Twig 全局变量,但我不知道应该把相关代码放在哪里:
I know about Twig globals, but i don't know where i'm supposed to put the relevant code:
$twig = new Twig_Environment($loader);
$twig->addGlobal('text', new Text());
{{ text.lipsum(40) }}
推荐答案
我会注册一个发生在每个请求上的事件监听器,可能是 kernel.request
事件.在侦听器中,您可以检查登录用户,如果是,则使用新消息计数更新会话变量.然后,您可以使用 app.session.msg_count
I would register an event listener that occurs on every request, probably the kernel.request
event. In the listener you can check for a logged in user, and if so update a session variable with the new message count. You can then access this session variable in twig with app.session.msg_count
这也有一个好处,你可以缓存它并且只在特定条件下更新,以避免对每个请求进行查询.
This also has the advantage that you can cache it and only update under certain conditions, to avoid querying on every request.
这篇关于在 Symfony 2 中分配全局 Twig 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!