Skip to content

Instantly share code, notes, and snippets.

@srinathweb
Created September 30, 2015 04:18
Show Gist options
  • Select an option

  • Save srinathweb/88ebbfb53642f841c0bd to your computer and use it in GitHub Desktop.

Select an option

Save srinathweb/88ebbfb53642f841c0bd to your computer and use it in GitHub Desktop.
twig
http://stackoverflow.com/questions/9842342/building-a-site-with-twig-php-template-engine
If you're using several PHP files then it's wise to create template renderer class, which will bootstrap Twig classes, set options and take care of finding and rendering requested templates:
<?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
$templateDirs
);
$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:
<?php
// Include our newly created class
require_once 'TemplateRenderer.php';
// ... some code
$news = getLatestNews(); // Pulling out some data from databases, etc
$renderer = new TemplateRenderer();
// Render template passing some variables and print it
print $renderer->render('index.twig', array('news' => $news));
Other PHP files will be similar.
Notes
Change settings/implementation to suit your needs. You may want to restrict web access to the templates directory (or even put it somewhere outside), otherwise everyone will be able to download template files.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment