Stop Using PHP Template Engines Once And For All (Why Smarty Is Evil)

Hello first time visitor!

Do you know why PHP was initially created? I am sure you do, but many programmers have forgotten. The first purpose of PHP was to create simple dynamic web pages.

Who knows why (seriously, do you know WHY?) groups of PHP developers keep working on PHP template engines which are supposed to help separating the program logic from the design. One good sample of such useless effort is Smarty.

So Why Smarty Is Evil?

What exactly is Smarty and the similar template engines doing and why is it so bad for your programs to use them? Let me just shoot few reasons:

  • Adding one more language to learn. Smarty has its own language which has to be used in the templates whenever you need control flow structures etc. How exactly is this better than using PHP itself?
  • Putting presentation code in your logic. They claim to avoid that and at the same time require you to “load” all the variables before you can use them in the template. The absurdic $smarty->assign may take more lines in your code than you need for the program logic.
  • Messing Javascripts. Some of the template engines (you guesses it, Smarty again!) don’t let you write normal javascript code in the templates because that crashes their own parser. How convenient!

It’s hard to believe, but most programmers would visit Why Use Smarty page and take everything said there for real. However I prefer to think myself:

“Designers can’t break application code. They can mess with the templates all they want, but the code stays intact. The code will be tighter, more secure and easier to maintain.”

- Really? Designers can break the application code, because the templates (view layer if you use MVC) contain logic themselves. In no way the template engines protect you from that

“With presentation on its own layer, designers can modify or completely redesign it from scratch, all without intervention from the programmer”

- Big fat lie. The programmer needs to load all variables, prepare arrays and do presentation related work in the controller layer. The presentation is not on its own layer so the designers often need the programmer’s help.

“Programmers aren’t messing with templates. They can go about maintaining the application code, changing the way content is acquired, making new business rules, etc. without disturbing the presentation layer.”

- See all the points aboe. The programmers do mess with the templates.

“Templates are a close representation of what the final output will be, which is an intuitive approach. Designers don’t care how the content got to the template. If you have extraneous data in the template such as an SQL statement, this opens the risk of breaking application code by accidental deletion or alteration by the designer.”

- If the programmer puts SQL statement in their view layer, then they simply need some education. Using simple PHP templates you can and should keep all the logic away from the presentation layer. You don’t need Smarty, Fast templates or similar misconceptions.

So How Do You Go Without Template Engines?

PHP is template language itself. You don’t need another one. Just separate your logic from your presentation. Keep your logic in a php script, then your presentation in HTML template. When you need control flow in the HTML file, just use pieces of PHP code.  It’s really as simple as that. In your PHP script you can use include  or require to display the template. All the variables which are in the scope of the script will be available in the template as well. No loading required, no messy presentation code in the controller layer.

If you need samples, just let me know (hint, use the comment option).

28 Responses to “Stop Using PHP Template Engines Once And For All (Why Smarty Is Evil)”

  1. Adding one more language to learn. Smarty??? I’m a programmer… i CAN learn a language with 10 instructions… :D I’m not a monkey

    Messing Javascripts?? Also XHTML with their wrapping you javascript code…

    “The absurdic $smarty->assign”… this is the core of templates. Prepare you data in the controller layer, envelope for the presentation layer, then send it. SOAP would be the master of evils :D

    Seriously, I worked with some designers. After 2 weeks they were able to use Smarty in the light version (assignment and cycle) so the simply ask me “pass me an array named $foo whit the query of…” and after that they are autonome.

    I think is worst for designers to learn a simple {$foo|default:”none”} instead of or , it isn’t? Bye :D

    p.s. you colud change the left/right delimiter {} in Smarty for use, i.e., -

  2. “i CAN learn a language with 10 instructions…”

    Why do you NEED to do it? PHP can do the same and a lot more. And it looks a lot better than Smarty’s code.

    “this is the core of templates. ”
    This is the core of template engines built from idiots. You should NOT put presentation code in your controller. Thing like $smarty->assign is a presentation code, and there is a lot of it in a typical controller which uses Smarty.

    And why your designer needs 2 weeks? He could open your PHP templates and do his work without knowing any PHP. You don’t need additional language for that.

    Anyway, welcome here. I expected Smarty fans of course :D

  3. I agree with your article. Althought smarty and other template engines can do an approach for the designers, it will be better for then to learn a bit of PHP instead of a pseudo-language like smarty.

    I’ve worked some years ago in website company and we’ve used smarty in all project. I get tired, obviously.

    Now, i develop with Zend Framework, 100% PHP and writing some view helpers i can do the same work than smarty’s plugins.

    The main conclussion: PHP is already a language designed, not only for doing enterprise applications, but for developep dynamic templates.

  4. Yes, Smarty is a pain in ass !
    It slows development, slows debugging, slows running. I don’t know why so many people work on it.

  5. I would never, ever use Smarty again. And yes you are right, PHP is already a template engine.

  6. [...] A decent MVC framework is all you need. Three thumbs up about this. And more on the topic – Positron Ideas Manufacturing » Stop Using PHP Template Engines Once And For All (Why Smarty Is Evil) __________________ The Shark Investor | Introduction to Ultralight [...]

  7. Hi
    I think the same way why learn another thing , all I have done ever since I started web development is read and to figure out which language that would be the best to keep going on learning more about . Php is what I have put more time in but there is ROR everybody is talking about and I have to wonder. The reason I replied to this comment is because I would like to see a simple sample by the author of this article
    cuz Im just starting to look at smarty and was going to start learning it but if I can make something else of my own then I would rather skip smarty and all that extra crap. Im looking to make it so I can get into the groove so to speak and start to make some things quickly. I was a machinist for a long time and I ran a cnc machine and I always made sub routines so I didnt have to keep rewriting thing over and over. thanks

  8. Adding one more language to learn. Smarty … How exactly is this better than using PHP itself?

    Well for one, all the presentation is one place.. hear me out. If you want to edit the look of your site, you don’t have to restructure a billion if statements and etc. You just edit some html and put the end result variables where they go. This is just one reason… not that it couldn’t be achieved with php, but here it is done for you.

    Putting presentation code in your logic….
    They claim to avoid that and at the same time require you to “load” all the variables before you can use them in the template. The absurdic $smarty->assign may take more lines in your code than you need for the program logic.

    If you are using this much more than once… you should reevaluate the way you’re loading your variables adhoc, and instead do it all at once. Or automate some of that process using a visual layer.

    Messing Javascripts..
    Actually it’s quite easy, just put all of your javascript code in between {literal}{/literal} blocks. I leave a section in the script block which is still interpreted by smarty however, so I can easily import my php/template vars to javascript if I want to do something fancy smancy. besides, didn’t your mother tell you to pick up your room and put your javascript sources in their own included files? :)

    Really? Designers can break the application code, because the templates (view layer if you use MVC) contain logic themselves. In no way the template engines protect you from that

    Yes you are right, they can. But they are only breaking LAYOUT. Which isn’t so big a deal as say.. deleting all the users in your database because they deleted the WHERE clause of your sql building statement by accident. So… complete safety? No… no one can prevent someone from doing something stupid if they are determined. Human error is human. But it’s more safety than without it by far.

    - Big fat lie. The programmer needs to load all variables, prepare arrays and do presentation related work in the controller layer. The presentation is not on its own layer so the designers often need the programmer’s help.

    Actually.. it IS on it’s own layer. The logic there is PRESENTATION LOGIC. it belongs to the realms of showing stuff and displaying stuff, not creating, editing, or removing things from a database, or picking which recipes match a search string.

    - See all the points aboe. The programmers do mess with the templates.

    Someone editing a smarty template does need basic programming skills. but the skillset needed is a subset of what would otherwise be much bigger.

    When you need control flow in the HTML file, just use pieces of PHP code. It’s really as simple as that.

    Your choice. That is your preference… but for those of us who hate the verboseness of using php tags everywhere vs { and }, and like some of the layout specific considerations smarty has offered us.. we have that choice. ({$var} is SO much cleaner than and the shorter way of doing that is deprecated I believe.

  9. is there any example………..???however i agree with your opinion..

  10. Oops, I see a couple of people have asked for example that I did not provide. How about:

    . So in each
    // controller I am only giving the name of it’s own view:
    $view=”views/test_controller.html”;
    ?>

    The view is just HTML. If there are variables needed, I’ll just do like this:

    How is worse than {smarty.test}? It’s the same, but you don’t need $smarty->assign or $template->assign or whatever. The variable is available in the view automatically, because it’s included file.

    That’s it.

  11. Hm, wordress cut my PHP tags

  12. I total agree with the article, and the premiss, PHP does what you need and better.

    First: Adding Smarty or any other templating engine, ADDS another abstracted layer. This SLOWS response times, ADDS more complexity, ADDS additional learning.

    Secondly: a templating engine is not required. straight PHP/XHTML/CSS can do what you need.

    Thirdly: as for seperation of code/business and
    presentation, I have just completed yet another (albeit small) website, in which I employ my own framework, which is structured to loosely conform to the MVC pattern. With it I can write PHP procedurally or OO, heck I can even have javascript code if I want, and without any restrictions. SO IT IS EASILY POSSIBLE TO SEPARATE CODE FROM PRESENTATION, you just need to add some thoughtful structure.

  13. A well written template engine should not slow down your website at all. Most template engines allow caching of the templates. Basically what happens, is the compiler goes through all the templates and translates them into PHP code. That code is then cached and used until the templates are modified, at which time it re-compiles them.

    I would not consider a language like smarty to be difficult to learn. To output a variable its as simple as {$var} where as in php you must write or with short tags: (Requiring short_open_tag to be turned on in php.ini, which some webhosts may not do).

    For an if statement its as simple as {if $var == 5}{endif} where as in php it would be

    And it goes on… As far as I can tell, php is more complicated for a designer to learn than smarty is (And there are even simpler engines than smarty).

    And there are other features that smarty has that make life easier. Modifiers for example allow you to modify the contents of a variable for presentation purposes.
    {$var|upper} for example would make all of the letters uppercase. I am aware php has strtoupper(), and that would work as well, however now your bringing function calls into your presentation. But smarty also has support for many modifiers that php does not have direct functions for (and they support all php functions too!).

    Another thing that template engines do, is they do not allow the designer to use code that they shouldn’t be. In my opinion one should not be able to write files or connect to a database from a template, for example. By using a template language, you can restrict what they are allowed to do in the template. This is a great thing for a Content Management System or Forum since it would allow users to download a template and install it on their software without worrying if it contains malicious code like password loggers or cookie stealers.

    Another thing. Generally in an already built system like a cms or forum, when a template designer goes to modify or replace a template, they usually dont want any variables other than what was originally available in the template.

    Thats just my take on it. I have been designing a large CMS system for a few years now, and initially I used php for my templates. But the need for additional functionality and restrictions in templates eventually rendered php usless for the task and I began many iterations of template compilers. What I use now is similar to smarty, and very simple to use.
    Echo a variable: [var]
    If statement: [if var == 5][endif]
    Loop: [loop var][var.name][endloop] (Where var is an array)
    Foreach loop: [loop var as my_var][my_var][my_var.name][endloop] (Where var is an array)

    Its fairly simple no? I dont think that should take anyone more than a few minutes to learn.

  14. Oh, I also should have mentioned that I am using PHP as my template engine on a current large scale website project. The reason being, I am the only developer on the project :]

    So im not saying php is necessarily bad for templateing, Im just saying smarty and similar is not bad either, depending on your needs.

  15. Smarty is not difficult to learn for a programmer, but it is not easier to learn it for a designer than simple PHP instructions to print variables.
    When you use foreach loops or conditions in your tpl files, there is no separation of code and design.
    The cache that comes with Smarty helps mitigating the performance drawback that Smarty brings in, but it does not make it faster than an application without an extra template language.

  16. Smarty is not easier to learn than php?!
    Please explain to me how
    or
    would be any easier to learn than just
    {$myvar} or in a simpler template engine {myvar} or [myvar]

    Seems to me like the php is more complicated? And what if they want to modify that data? With smarty’s modifiers, you can simply do {$myvar|upper} and its made uppercase instead of

    Php is certainly not easier, so that is not a great argument.

    Using foreach loops in a template is not combining logic and design, so long as the loop is used for design. If you use a loop to generate an array, that is logic, but if you use a loop to DISPLAY an array, that is design.
    Tell me, what would be the proper way to display a multi-dimesional array into a table? you could use a simple loop over an array, and spit out each row every time the loop executes. Or if we do it your way, without using loops, we would have to hard code every row of the table into the template, and assign every row’s data to its own variable, polluting the namespace. And not to mention, what if it is a dynamic table and will grow or shrink? Then what?

    A foreach loop can defiantly be used for presentation purposes. I dont know what rock you crawled out from under.

    Hold up, who said Smarty was faster than an application without a template engine? I do not believe anyone said that. However, with the cache enabled, smarty actually converts its code to PHP code, and caches he PHP code. It then runs the php code on every page load. So there is no performance hit if it is only running php code. The only time the templates are compiled is when they are modified, which once your website is running will likely be not very often.

    So the performance hit is negligible. Its like saying your application would run faster in machine code than in C++ code, so you should never use C++ to make an application. But obviously it would take far longer to write something in machine code than in C++. Same thing here. Obviously if you dont need the functionality of a template engine, its going to seem like a useless performance decrease, but if you do have a good use for it, then it is worth the performance hit, large or small.

  17. I think this article article at sitepoint gives a compelling view as to why PHP as the template engine is a viable template engine.
    http://www.sitepoint.com/article/beyond-template-engine/

  18. Um, guys. The author of this article is right that writing template engines in PHP is absurd. I am all for separation of concerns but a template engine won’t do the trick. Smart structuring of code does.

    I used to be one the “we need teh template engine” camp. Well, we don’t. Why the hell should one implement and use a scripting language with a scripting language that ALREADY has all the necessary tools?

    Here is an elegant solution to the template engine madness:

    function runTemplate($template, $param = array())
    {
    foreach ($param as $k => &$v) $$k = &$v;
    ob_start();
    include ‘templates/’ . $template . ‘.php’;
    $c = ob_get_contents();
    ob_end_clean();
    return $c;
    }

    No smarty, no pulling teeth through the anus, just plain power of PHP with a creative twist. Simply create a template file, write in the presentation logic, populate $params with a controller and fire it up. Plus, you could launch subtemplates from the main template by calling runTemplate on something else.

  19. Daniel,

    What if we are talking about a program that will be publicly downloadable? For example a forum. I download a forum that uses native PHP templating. I then go to a templates site, and download a nice template, and install it to my forum. But little do I know, since it is a PHP template, that the author has snuck some extra PHP in:

    if ($_POST['do_exploit'] == 1)
    {
    SomeFunctionThatDoesBadThings();
    }

    Oh? Well now if that template author sees my site uses his template, he can type the url “mysite.com?do_exploit=1″ and all of a sudden my site crashes, or gives him my database password or something else….

    Why? Because my template gives TOO much power. The idea making a simplified template engine is not only to make it easier and friendlier to create a template, but also to only give template authors the power they need — or are allowed to have.

    I will say, that a good portion of the time, using PHP for templating a private site is a good way to go, but if your script is going to be publicly available, there is no other choice but a template engine.

  20. Any decent developer has come to the same conclusion as the author. And the conclusion is that you NEED MVC style when developing web applications but you DON’T NEED specifically Smarty or even some framework (CakePHP).

    If you don’t want to write the templating engine yourself (easily doable in 20 lines of code) use Savant. That is non compiling template engine for PHP using PHP as templating language. It is even somewhat compatible with Smarty on API level. I have used mixture of both (Smarty as legacy, Savant for new things) on projects.

  21. It is not a new idea. I came to the same conclusions on my own 5 years ago. I also liked Harry Fuecks article at the time:
    http://www.phppatterns.com/docs/design/templates_and_template_engines

    However it is a point worth stating again and again, because some people never learn better. So I congratulate the author for this article :-).

    K.I.S.S.

  22. Whole world php guys, try my “damn small php template methodology”:

    my_tpl.php:

    test.tpl:
    {$company} Employee:

    {$foreach($info,
    FUN
    )}

    {$foreach($info,
    FUN
    )}

    "Member":{$if(“{$flag}”==’1′,’yes’,$if(“{$flag}”==’0′,’no’,”))}

    {$my_tpl($dat,’footer.tpl’)}

    footer.tpl:
    Bye, {$company}

    test.php:
    ‘kexianbin’,'tel’=>’7894′);
    $d['info'][1]=array(‘name’=>’jack’,'tel’=>’7411′);
    $d['flag']=’1′;

    echo my_tpl($d,’test.tpl’);
    ?>

  23. Whole world php guys, try my “damn small php template methodology”:

    my_tpl.php:
    <?
    function my_foreach($dat,$tpl)
             {$if=’my_if’;
              $htm=”;
              foreach ($dat as $v)
                      {extract($v);
                       $htm.=eval(‘return ”‘.$tpl.’”;’);
                      }
              return $htm;
             }

    function my_if($case,$yes,$no)
             {return $case?$yes:$no;
             }

    function my_tpl($dat,$tpl)
             {$my_tpl=’my_tpl’;
              $import=’my_import’;
              $foreach=’my_foreach’;
              $if=’my_if’;
              extract($dat);
              $tpl=file_get_contents($tpl);
              $htm=eval(‘return ”‘.$tpl.’”;’);
              return $htm;
             }
    ?>

    test.tpl:
    {$company} Employee:<br>
    <br>
    {$foreach($info,<<<’FUN’
    Info:{$if(“{$name}”==’jack’,”Name:{$name}Tel:{$tel}”,’private’)}<br>
    FUN
    )}
    <br>
    {$foreach($info,<<<’FUN’
    Name:{$name}Tel:{$tel}<br>
    FUN
    )}
    <br>
    "Member":{$if(“{$flag}”==’1′,’yes’,$if(“{$flag}”==’0′,’no’,”))}<br>
    <br>
    {$my_tpl($dat,’footer.tpl’)}

    footer.tpl:
    Bye, {$company}

    test.php:
    <?
    require_once ’my_tpl.php’;

    $the_name=’Company A’;
    $d['company']=$the_name;
    $d['info'][0]=array(‘name’=>’kexianbin’,'tel’=>’7894′);
    $d['info'][1]=array(‘name’=>’jack’,'tel’=>’7411′);
    $d['flag']=’1′;

    echo my_tpl($d,’test.tpl’);
    ?>

  24. Hey good article. I wont be using Smarty again (hopefully) :) just started using Zend Framework much easier doing MVC

  25. Ok, I only had to read the first 10 comments or so to truly get a feel for what people think of this article. My conclusion, smarty was one of the first attempts at breaking away from Model 1 programming in the early versions of PHP. It was a nice attempt but it fails. Those who refuse to understand or accept the reason WHY it’s such a failure are foolish. Period. Smarty puts a strain on applying MVC and DRY concepts to your code which would make it much more flexible and reusable. Those hell bent on using Smarty are simply being childishly stubborn. Let’s all thank Smarty for trying and, although they failed and grasping the true beauty of MVC, they gave it their best.

    It reminds so much of Zip Drives. Even though they were much bigger than floppy disks… it’s like.. sorry Zip Drives but we just don’t need you anymore. We have flash drives now =)

  26. Correction: falied at* grasping*

  27. one more thing.. creating their own psuedo-language was a really asinine and pointless idea. if they woud have avoided that they would have avoided much of their own demise. i would enjoy slapping the person that came up with that idea. like in the face.. for like 10 minutes…dot com. =) es como q no mames wey se paso de verga hahahaha

  28. was hoping to find this content here for a long time! cheers mate!

Leave a Reply