Twig, the next generation template engine for PHP en

By drm on Tuesday 9 February 2010 20:50 - Comments (12)
Category: Development, Views: 28.047

I've been using Smarty 2 for about 7 years, and, while Smarty 3 is still in beta, Twig just popped up in the scene. Notable Smarty opposer Fabien Potencier was apparently converted by this template engine, so Twig must either be magic, or excellent, or both.

One of the major drawbacks of Smarty is that it is bloated (think of all those "internal functions" next to the two walruses of classes), renders fairly unreadable source code and is not that well extensible. Some of the syntax choices in smarty aren't that practical either... How many times have you typed {foreach $items as $value} in a Smarty template? I have about a gazillion times. And who the H thought of that abominable {section ...} thing?).

Of course, I also need to point out that it is actually quite fast, it makes for an excellent alternative to writing templates in pure PHP, and there has never been any template engine nearly as simple and at the same time powerful as Smarty. Not to mention the fact that it was actually the first one to come with a compiler paradigm. Well, I have used it for such a long time, I think that counts as enough defence.

Ever since PHP is evolving more and more into an object-oriented language, and even more so, the community is gaining more and more good developers, there was bound to be someone to say: "Smarties are for children, real men just gnaw on wood". So Twig is born. And a prodigy it is.

The set-up is very straight forward. A solid compiler, with great extensibility. You can hook into the compiler's syntax tree with your custom nodes, change the syntax by defining delimiters, easily read the generated code, and redesign every part of the engine because of it's design-by-contract implementation.

Here are some pointers if you're used to smarty:
Default delimiters, the $ sign and data types
Default, Twig uses {{ var }} delimiting for variable output, and {% ... %} for control structures. The dollar sign is a goner, so get used to that. There is no difference between an array and an object, so you can write {{ var.property }} for both arrays and objects. A slight difference is that in case var is an object, Twig also checks if the var has a getter for the property in either form property() or getProperty().

For-loops and sections
foreach is called for, and sections need to be rewritten to for-loops as well.

code:
1
2
3
{% for key, value in items %}
   {{ key }} contains {{ value }}
{% endfor %}

Special context-sensitive variables are available in the loop-variable.

modifiers and functions
Twig supports Smarty-style modifiers, though parameters are passed within parentheses: {{ var|modify("with argument") }}. Functions are supported as well, and can be implemented by writing extensions to the compiler.

Cool stuff that smarty doesn't do
  • Template inheritance. Define a layout in one and populate the blocks in another template.
  • Macro's, which are tiny pieces of template code, reusable as a function in the rest of the template. You can store macro's in external templates, and import them for reuse.
  • Access a parent context reference, which enable you to identify for example which loop variable you want to access in a nested loop, the inner or the outer one.
  • A generic expression parser, which enables you to set and define complex expressions wherever an expression is allowed
And probably I'm leaving out a whole bunch of other nice features. Read more about it in the Twig documentation, and get inspired.

I hope a 1.0 version will see the daylight soon. I think it is a very welcome attribution to the community, so let's thank Armin Ronacher for kick-starting Twig, and Fabien for his conversion to the one true faith: PHP is no longer just a template engine. ;)

PS: If the first question that comes to mind is Why use a template engine if you're already using PHP, never mind. There are plenty valid points to use a separate template engine. There a plenty valid points against it too. I don't really care. Smarty has done the job outstandingly, and as long as the deemed successor compiles into PHP code, I'm happy.

Volgende: My top 5 dos and don'ts of self-explanatory programming 03-'10 My top 5 dos and don'ts of self-explanatory programming
Volgende: VirtualBox is more free than you might think 02-'10 VirtualBox is more free than you might think

Comments


By Tweakers user Freeaqingme, Tuesday 9 February 2010 21:05

What is its added value compared to what PHP brings by itself?

By Tweakers user kokx, Tuesday 9 February 2010 21:07

Still, i'm going to ask that question to you :). Templating engines only limit what you can do in your view, and that way you will always end up with template-related code in your controllers. If you use PHP itself, you can do anything that PHP can do.

Also see: http://nosmarty.net/

By Tweakers user YopY, Tuesday 9 February 2010 21:39

So, err, why is this better than Smarty or basic inline PHP again? I wasn't able to discern that from the post.

By Tweakers user kwaakvaak_v2, Tuesday 9 February 2010 22:24

There is no such thing as better, just different approach in separating data and html in a more frontend developer friendly way ;)

By Tweakers user drm, Tuesday 9 February 2010 22:53

First off, I'm not telling anyone to use a template engine, I'm just saying that if you do, Twig is really something to look into.
freakingme
What is its added value compared to what PHP brings by itself?
For me there are two simple reasons. One is brevity, the other is simplicity. Regarding brevity, short tags in PHP are comparable, but imo not as simple or even short. That is a matter of taste, I agree. Secondly, I tend to have less trouble explaining Smarty to non-PHP front-end developers than Smarty PHP.
kokx
Still, i'm going to ask that question to you :). Templating engines only limit what you can do in your view, and that way you will always end up with template-related code in your controllers. If you use PHP itself, you can do anything that PHP can do.
I have never had that experience with Smarty, and since Twig seems more powerful and more easily extensible, I'm pretty sure I won't have that experience with Twig either.
really, this is one of the lamest and most disrespectful flames I have read ever. Fortunately, they can't be taken seriously if they really suggest PHPTAL and XSLT as alternatives to Smarty. It surprises me they didn't suggest JSP :z

[Comment edited on Wednesday 10 February 2010 09:55]


By Tweakers user Afvalzak, Tuesday 9 February 2010 23:54

explaining Smarty to ... than Smarty.
Getting late right ;)

Thanks for the blog it's always nice to read about something other then the usual suspects ;-)

[Comment edited on Tuesday 9 February 2010 23:54]


By Tweakers user PeterSelie, Wednesday 10 February 2010 08:42

@drm I am (and have been) using XSLT as my primairy template engine for quite a while and wouldn't have any arguments on why to change to something else, can you enlighten your opinion about the engine?

By Tweakers user drm, Wednesday 10 February 2010 10:02

afvalzak: Getting late right ;)
Indeed :P
SoaDmaggot: @drm I am (and have been) using XSLT as my primairy template engine for quite a while and wouldn't have any arguments on why to change to something else, can you enlighten your opinion about the engine?
I'm not saying you need to change to something else. It is just not a fair comparison. XSLT is way more complex than Smarty, and the declarative approach is even harder to explain than plain PHP.

To be frank, my opinion about xslt is that it is one of the greatest techniques out there. I have loved XSLT from the first moment I tried it, and actually used it as a template engine for some websites back in the php4 days. But an easy switch from Smarty to XSLT is just not realistic.

By Tweakers user PeterSelie, Thursday 11 February 2010 12:50

drm: I'm not saying you need to change to something else. It is just not a fair comparison. XSLT is way more complex than Smarty, and the declarative approach is even harder to explain than plain PHP.

To be frank, my opinion about xslt is that it is one of the greatest techniques out there. I have loved XSLT from the first moment I tried it, and actually used it as a template engine for some websites back in the php4 days. But an easy switch from Smarty to XSLT is just not realistic.
Ok, I misunderstood your previous comment about XSLT and Smarty not being comparable. I thought your comment was ment as a negative point towards XSLT :)

By magallanes, Thursday 31 March 2011 16:28

The main problem with twig is that it is support-less, smarty is bloated but the official page is quite decent and is full documented. While twig... the last update was 3 years ago... :-/ may be it can be cool for small project but not for a professional project.

and about XSLT.. is a mess and it must be supported by the browser and you know Iexplorer is still widely used.

but my wish (and i think it is possible) is not a template system that do everything and even can do custom code, instead i want a template system compatible amongst other system, let's say, if i have a myawesomepage.tpl then i want that it can be compatible amongst php, python, java and such.

By xially, Wednesday 30 November 2011 15:14

Also you can look what is the difference in perfomance Twig and Smarty. http://umumble.com/blogs/php/249/
I think the perfomance is also very important thing which has to be considered when you deciding to use this template engine or not.

By Fed, Monday 26 December 2011 21:53

Fabien Potencier wrotes Twig. He were totally versus template engines, and now finally he realize that PHP sucks in managing the presentation layer.

Twig use the syntax of Django, one of the best framework for Python. In my opinion, both Twig and Smarty are overloaded with functionalities.

Here there is a simple benchmark that test both. Behind the performances which are not that different, what surprised me is that Smarty take almost 1Mb of space and Twig 700Kb:
http://www.phpcomparison.net

In my opinion are both overloaded with code, often not either useful. My favorite is Rain, faster, smaller (70Kb), easier to install and to use. In a word, better!
http://www.raintpl.com

Comments are closed