twigHow to use PHP variables in Twig?
Twig is a templating language for PHP, and it allows you to use PHP variables in your Twig templates. To do this, you need to pass the variables to the Twig environment when you create it.
$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader);
$name = 'John';
$twig->addGlobal('name', $name);
The above code creates a Twig environment and adds a global variable name
with the value John
. This variable can now be used in any Twig template.
Hello {{ name }}
Output example
Hello John
Code explanation
$loader = new Twig_Loader_Filesystem('templates');
- creates a Twig loader object which is used to load Twig templates.$twig = new Twig_Environment($loader);
- creates a Twig environment object which is used to render Twig templates.$name = 'John';
- creates a PHP variable with the valueJohn
.$twig->addGlobal('name', $name);
- adds the PHP variablename
to the Twig environment as a global variable.Hello {{ name }}
- uses the global variablename
in a Twig template.
Helpful links
More of Twig
- How to embed YouTube videos in Twig with PHP?
- How to integrate Twig with Yii2?
- How to use Twig in PHP to get the current year?
- How to parse XLSX in Twig with PHP?
- How to use XOR in Twig with PHP?
- How to parse XML in Twig with PHP?
- How to use Slim/Twig-View in PHP?
- How to use Twig with a PHP MVC framework?
- How to use a Twig file in PHP?
See more codes...