Home > php, python > Jinja2-like template for PHP

Jinja2-like template for PHP

My primary language is Python. When I need to do a simple webpage or a REST API, I use Flask with its built-in Jinja2 template engine.

However, I started to work on a project with some friends and our UI developer chose PHP for the frontend. As I also want to contribute to the UI, I looked around the PHP template engines if there is someting similar to Jinja2.

It turned out that Jinja2 was ported to PHP! It’s called Twig and it’s almost the same. So if you use Flask, Twig is a natural choice for PHP.

There are also several MVC frameworks for PHP but I don’t use any (yet?). I have a PHP file (the controller), and a corresponding HTML file (the view, i.e. the template). Let’s see a simple example:


require_once 'vendor/twig/lib/Twig/Autoloader.php';

$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader, array(
    // 'cache' => 'compilation_cache',

$context = array(
    'name' => 'Twig',

echo $twig->render('index.html', $context);


Hello {{ name }}!

It will print the text “Hello Twig!” to the screen.

What happens? The index.php file is the controller. Here you collect all the data that you want to print in the resulting HTML output. These data are put in a hash table (dictionary), and it’s passed to the template file index.html.

You can enable the cache in the index.php file. In this case the view will be “compiled” to a PHP file, making it faster. However, during the development you’d better switch it off. As I noticed, when I change the source code, the cache is not always updated automatically. So if you enable the cache and change the source, don’t forget to purge the cache.

Project layout
My project structure looks like this:

├── compilation_cache
├── index.php
├── templates
│   └── index.html
└── vendor
    └── twig
        └── lib
            └── Twig
                └── Autoloader.php
                └── ... (other files of the Twig template engine)

For security reasons, I think it’s a good idea to move the “vendor” folder somewhere else that is not accessible via the http protocol. That is, if your project is served from your “~/public_html” folder, move the “vendor” folder outside of “~/public_html“. I’m not sure but it may be true for the “compilation_cache” folder too.

Categories: php, python Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: