<?php // Use correct path to Twig's autoloader file require_once '/path/to/lib/Twig/Autoloader.php'; // Twig's autoloader will take care of loading required classes Twig_Autoloader::register(); class TemplateRenderer { public $loader; // Instance of Twig_Loader_Filesystem public $environment; // Instance of Twig_Environment public function __construct($envOptions = array(), $templateDirs = array()) { // Merge default options // You may want to change these settings $envOptions += array( 'debug' => false, 'charset' => 'utf-8', 'cache' => './cache', // Store cached files under cache directory 'strict_variables' => true, ); $templateDirs = array_merge( array('./templates'), // Base directory with all templates ); $this->loader = new Twig_Loader_Filesystem($templateDirs); $this->environment = new Twig_Environment($this->loader, $envOptions); } public function render($templateFile, array $variables) { return $this->environment->render($templateFile, $variables); } }Don't copy-paste, this is just an example, your implementation may be different depending on your needs. Save this class somewhere
Usage. I'm going to assume that you have a directory structure similar to this:
/home/www/index.php
/home/www/products.php
/home/www/about.php
Create directories under webserver's root dir (/home/www in this case):
/home/www/templates # this will store all template files
/home/www/cache # cached templates will reside here, caching is highly recommended
Put your template files under templates directory
/home/www/templates/index.twig
/home/www/templates/products.twig
/home/www/templates/blog/categories.twig # Nested template files are allowed too
Now sample index.php file: