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;
}
In Twig:
Total messages: {{ app.user.messages|length }}.
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?
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) }}
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.
you need to create and register a twig extension. twig extensions can provide globals in the same fashion like your code example. i'll paste you some code on which you can base on...
first create the extension class in any bundle
class FooBarTwigExtension extends \Twig_Extension
{
public function getGlobals()
{
return array(
'foo'=> $this->bar,
);
}
}
then register it as twig extension in the bundles service definition
<service id="acme.foo_bundle.twig_extension" class="Acme\FooBundle\Twig\FooBarExtension">
<tag name="twig.extension" />
<argument ...>
</service>
afterwards you can access the variable in twig
<h1>{{foo}}</h1>
if you want to use lazy initialisation you might want to pass in an object and call a message of that object, so the message count will only needed when it is displayed.
<h1>{{messaging.countUnread}} new messages</h1>
another way would be to implement a twig function that fetches the unread message count for the current user
If your User entity has a getUnreadMessages()
method, you can use {{ app.user.unreadMessages }}