I found this Sitepoint lesson very simple. I simplified and summarized the steps:
It assumes basic command line knowledge and Composer .
Install Twig - Composer is probably the easiest way for most people. Run composer require twig/twig
in your docroot. This will create composer.json
and composer.lock
if you do not already have them, and the vendor
directory into which Composer will load Twig and several Symfony dependencies it uses. Composer will also generate some startup files.
create the templates
directory for your Twig source files (personally, I would like to put this above docroot for security)
- create a sample
index.html.twig
template in this directory - create a
bootstrap.php
file (a few lines of PHP to load and initialize Twig (and tell you where to find the templates) - create an
index.php
file to demonstrate loading and parsing the template. It:- boot loader
- defines some data (in an array) for filling tags in a template
- uses the Twig render () method, which defines the template and data array
Visit the second PHP file in your browser and you should get a processed Twig template.
boostrap.php:
<?php // Load our autoloader require_once __DIR__.'/vendor/autoload.php'; // Specify our Twig templates location $loader = new Twig_Loader_Filesystem(__DIR__.'/../templates'); // Instantiate our Twig $twig = new Twig_Environment($loader);
index.php:
<?php require_once __DIR__.'/bootstrap.php'; // Sample data $foo = [ [ 'name' => 'Alice' ], [ 'name' => 'Bob' ], [ 'name' => 'Eve' ], ]; // Render our view echo $twig->render('index.html', ['foo' => $foo] );
templates / index.html.twig:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Twig Example</title> </head> <body> <ul> {% for item in foo %} <li>{{ item.name }}</li> {% endfor %} </ul> </body> </html>
The next step is to change your index.php to the appropriate front-end controller so that it can handle multiple templates.
The guide also mentions things like caching generated templates.
source share