twigHow to use Twig with PHP?
Twig is a templating engine for PHP. It allows developers to write HTML templates with a simple syntax that is easy to read and maintain.
<?php
require_once 'vendor/autoload.php';
$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader);
echo $twig->render('index.html', array('name' => 'Fabien'));
This example code will render the index.html template located in the templates directory, and pass the name variable with the value Fabien to the template.
Code explanation
require_once 'vendor/autoload.php';- This line loads the Twig autoloader, which is necessary for Twig to work.$loader = new Twig_Loader_Filesystem('templates');- This line creates a new Twig loader object, which is used to locate the template files.$twig = new Twig_Environment($loader);- This line creates a new Twig environment object, which is used to render the templates.echo $twig->render('index.html', array('name' => 'Fabien'));- This line renders theindex.htmltemplate, and passes thenamevariable with the valueFabiento the template.
Helpful links
More of Twig
- How to use yield in Twig with PHP?
- How to parse XML in Twig with PHP?
- How to include a Twig file with PHP?
- How to use Slim/Twig-View in PHP?
- How to prevent Template Injection in PHP Twig?
- How to use a Twig variable in PHP?
- How to check if a string contains a substring in PHP Twig?
- How to use a switch case in PHP Twig?
- How to set a variable in PHP Twig?
- How to use the OR operator in Twig and PHP?
See more codes...