How to inject global variable into Twig

My computer develop environment

1
2
3
4
5
6
"require": {
"php": ">=5.6.10",
"symfony/symfony": "2.8.*",
"twig/twig": "1.35.*",
...
}

In project development, you will often need to display the user’s name, avatar, etc. in the top navigation bar of the website.
By default, Symfony using the Twig template engine to store account information into the app.user.username after logging in, but it will not be able to get other user information in app.user.

I have a few solutions for this problem

Using PHP $_SESSION

storing the user’s account information into the session as key-value pair after the user logs in.

Using Twig Extension, Query user information by user account

Twig Extension can refer to my previous blog

Add variables using Symfony’s global method

I think this is the most beautiful way.

1
$this->get('twig')->addGlobal('header', "http://xxx.jpg"");

When you want to use it in a twig file, you only need a simple output.

1
{{ header }}

Thank you for reading.
This post is copyrighted by Liyuliang’s Blog.
If reproduced, please indicate the source: Liyuliang’s Blog
This blog uses Creative Commons Attribution-NonCommercial-Share-Sharing 4.0 International License Agreement to license.


Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×