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 use a Twig file in PHP?
- Where can I convert PHP to Twig online?
- How to use a PHP function in Twig?
- How to check if a string contains a substring in PHP Twig?
- How to use Twig in PHP to get the current year?
- How to use Slim/Twig-View in PHP?
- How to use the Twig library with PHP?
- How to use yield in Twig with PHP?
- How to use a switch case in PHP Twig?
See more codes...