PHP Twig Template Tutorial – A fast, simple and lean templating engine for PHP

Recently, we have been looking and testing different templating engines for PHP.  As part of our research, we came across Twig, a modern template language for PHP. We immediately liked the fact that Twig was a stand-alone engine, and not a complete Web framework.

Some of the features of Twig:

  • Compiles templates into plain optimized PHP code
  • Template inheritance. Define a layout in one template and populate the blocks in another template.
  • You can define and use macros

In this PHP TWIG template tutorial, I’ll explain how to use Twig.

The project

First, let’s have alook at the file structure of the project:

PHP Twig template tutorial

  • compilation_cache: Directory where the compiled PHP templates will be written too.  Please note that this directory must be writable by the Web server user.
  • css: Used to store the CSS files.
  • lib/Twig: The actual TWIG templating engine.  The latest version of the engine can be found here.
  • templates: Where all the templates will be stored.
  • demo.php: Main PHP file for the project.

The PHP source file

The demo.php file acts as the controller in our example.  It basically does the following:

  • Line 2-10: Sets up the TWIG templating engine.
  • Line 12: Loads the listview.html template.
  • Line 14-15: Retrieves the data from the model (is this case, a simple JSON array).
  • Line 18-21: Invokes the templating engine, injecting  the pageTitle and docs variables.  The display() method will output the resulting HTML directly, but if you want to assign the result to a variable, you can use the render() method instead.
demo.php

demo.php

The HTML template files

Now, let’s have a look at the template files.

base.html

base.html

The base.html is the base template that listview.html will be extending.  This is the equivalent of the master page in .Net.  In our case, we define 4 blocks that we’ll be able to override/extend in child templates:

  • line 4-8: head block
  • line 7: title block
  • line 11: content block
  • line 13-15: footer block

Please note that in the case of the head & footer blocks, a default rendering is defined, so it may not need to be extended.

listview.html

listview.html

Now, let’s have a look at the listview.html file.  This is the actual template file that is loaded on line 12 of demo.php.

  • Line 1: Specifies that this template extends (or is a child) of the base.html template
  • Line 2: Simple TWIG comment
  • Line 4: Overrides the title block defined on line 7 of base.html.  In this case, we’ll just display the pageTitle variable that was injected on line 19 of demo.php
  • Line 7-22: Overrides the content block defined on line 11 of base.html.
    • Line 8: Display the pageTitle variable inside the <H1> tags
    • Line 11-20: Loop through all the elements in the docs array loaded on line 15 of demo.php
    • Line 14: Apply the summaryitem.html template to all of the elements in docs array.
    • Line 15-17: Apply the detailitem.html template only to the first 6 elements in the docs array.
summaryitem.html

summaryitem.html

The summary.html template demonstrates two very powerful features of TWIG:

  • Line 2-3: How you can easily access the fields of a docs element
  • Line 2: The use of the upper filter.  Other filters include urlencode, title, striptags, join, etc.  For more information, please visit the TWIG web site.
detailitem.html

detailitem.html

Finally, the detailitem.html templates shows how you can display all the fields of an element.

Conclusion

So far, we have not found any major problem using TWIG.  The performance is really good (in fact, according to author, TWIG is faster than all other PHP templating engines) and it is easy for our HTML integrators to learn the language.

We currently have a pilot project using TWIG and we’ll keep you posted on the results.

Thanks to Daniel for helping in building this PHP TWIG template tutorial.

Bonus

I just found a presentation about TWIG that the author gave the 2009 PHP/Zend conference.



This entry was posted in Web Development. Bookmark the permalink.

24 Responses to PHP Twig Template Tutorial – A fast, simple and lean templating engine for PHP

  1. Dan says:

    Very nicely done!

    • Sébastien Giroux says:

      Thanks! Couldn’t have done it without you! Now, I’d like to figure out a way to do a video tutorial and post it on Youtube… That would really help understanding the concept.

  2. ericc says:

    Excellent tutorial !
    Clear and simple … Should be part of the official documentation ! Seriously as it really lack some example(s) !

    Just a remark : It’s a shame that we can’t copy/paste the code !
    screen-shot from netbeans are good as colorized code make it easier to understand but allowing us to copy and then paste directly in our IDE, can help us to follow your examples easily (and modify it to test)
    btw : Do you know if a plugin exist for netbeans ? like those for Smarty ?

    Thanks again

    • Eric, thanks for the comment!

      I agree with you that it would be a lot better if you could copy/paste the code. I just have not found the right WordPress plugin to do that yet.

      For the Netbeans plugin, I have not found one yet. If you happen to find one, please let met know!

      Sébastien

  3. Alexander says:

    Unfortunately this tutorial doesn’t cover the most-wished case with multiple pages. Now we have a single demo.php which invokes some files that extend each other.

    Let’s turn to a real life:
    - http://example.com/
    - http://example.com/about
    - http://example.com/trips/italy

    What folder structure will be? Should we create index.php, about.php and /trips/italy.php with loaders within and keep associated templates separately (thus doubling files) or there is more intelligent way?

    Sébastien, could you be so kind and bring the light of knowledge, please. :)

  4. Ruben Tan says:

    I’ve been using Twig for 2 projects now, and I think it is still lacking in some of the most important tools that Smarty comes packaged with. Firstly, debugging. Debugging in Twig is a PITA, and that’s an understatement. I know that there’s a debug extension (and I’m using it), but all it does is dump the variables onto the HTML itself, which is next to impossible to read and analyze.

    In Smarty you can use {debug} to dump out all variables, which are neatly sorted per block and per include. That was really useful when building large, complex composite view pages, like 99% of all web 2.0 development nowadays. Debugging should come standard on templating engines, but Twig seem to have included it as an afterthought.

    Secondly, the quirkly template inheritance model. I have a block in header.tpl, which is included in master.tpl, which is then extended by page-public.tpl, which is then extended by frontpage.tpl.

    There’s a block “login” defined in header.tpl, but in frontpage.tpl, it does not make any calls to the block at all. Strange, considering that the exact same structure worked in Smarty. I had to copy and paste everything in header.tpl into master.tpl to have it work.

    I’m guessing block inheritance don’t work on included files further up the inheritance scope? This is one of the things that irked me.

    And finally, the document is lacking. Like, seriously lacking. There were painfully little information on how to roll your own extensions, and documentation there only covered basic usage. Too little coverage of use cases, and too little information.

    On the flip side, love the syntax, love the generated compiled files (just take a look at Smarty’s compiled files and I dare you not to puke), and love the lean code. I will continue to use Twig and hopefully once I’m done with my current project I’d be able to fork Twig and start adding in these “missing features” (with debug on the top of my list).

    • Thanks for your reply. To be honest, I don’t think we are using it as heavily as you are. Thus, we haven’t had any problems with the inheritance or debugging.

      As Symfony2 is gaining traction (more and more people are talking about it), I think TWIG will get more solid and more documented.

      Good luck with your projects!

  5. Tuck says:

    Thanks for tutorial! I have one question that I haven’t been bake to quickly answer. Using twig’s macro function, is it possible to include php code, or are macros limited to HTML for security reasons? To be more specific, would it be possible to run php code within a macro that has access to the variables being consumed by the twig template?

  6. Hi Sébastien,

    Very easy to follow and very nicely written. Thanks for sharing!
    I just have one request,
    Can you add a download link of the project?
    This will really help!

    Thanks & Regards,
    Sagar Ranpise

  7. Helen Neely says:

    Thanks for this nice example. Have used templates in Java and Python, but didn’t know you could do something similar in PHP. will check out Twig to see how simple it is to learn.

    Nice job.

  8. Han Chung says:

    I just created a demo for people to test out twig at demo.codefunc.com. Hope this is of use to all those trying to learn twig!

  9. samir says:

    nice tutorial, i would like to suggest that the code displayed above should not be displayed as image.

  10. hello ppl. any twig ready made for joomla.

  11. zoel says:

    thanx for your tutorial, it help me to develop any webapps ….;-)

  12. Chella says:

    Hi,
    This is very nice and neat to understand the twig engine. It was helpful to me to extend it in my project.,

    Thanks!

    Chella

  13. Sudhakar K says:

    Symfony twig website lacks these type of basic tutorials.
    Basic start is a must for beginners.
    Thanks, good work.
    Try to post a “Step by step” tutorial on twig, with a small form, a loop (list item), a mini website.
    If you publish “step by step” please send a link to my mail.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>