Why a templating engine?

Can someone enlighten me as to why would I use a templating engine like Smarty when I could just flush templates into variables with a really simple class like the following? :


Class Template{
	public function __construct($file,$variables=null){	
		return $this->getTemplate($file,$variables);		
	}	
	private function getTemplate($file,$variables){
		if(!is_null($variables)){
			foreach ($variables as $name => $val) {
				$varName=Text::machine_name($name);
				$$varName=$val;
			}
		}			
		if(is_file($file)){
			ob_start();
	    include($file);
	    $this->html= ob_get_clean();
		}
	}
	public function dataAttributes($attr){
		if(!is_array($attr)) $attr= array();
		$attributes='';
		foreach ($attr as $key => $attribute) {
			$attributes.=' data-'.$key.'="'.$attribute.'"';
		}
		return $attributes;
	}
}


I just had to start working with Smarty and feel it’s quite odd and defeats the purpose but of course maybe I’m wrong and it’s just fear to the new. I would really appreciate your comments.

Many thanks,

Andres

The motivations behind templating engines include…

Many thanks for the above. I had a read and still not convinced templating engines are for me. Reasons are:

  1. More concise.

<?php echo $var ?>

  • vs -

{{ var }}

(Most projects consider PHP’s shorthand <?= to be unsafe because short_open_tag is often off.)

Don’t really regard this as an advantage as in my humble opinion it helps only in obscuring the code with some foreign syntax. Text editors give visual clues that disappear when we abstract code like that. Agree that the php tag is a bit long but I really don’t mind it. “php” + tab key will give me “<?php ?>” in my text editor.

  1. Enforce separation of concerns.

PHP templates require self-disciple to not do more than you should in a template. Libraries like Twig make it impossible to do more than you should. This is especially good when designers (non-programmers*) start working on the templates.

*And let’s face it, even actual programmers will botch this sometimes.

The class I posted above does just that. It will only make available to the template the variables that you pass onto it. It will also store the output in a variable so that you can print it at a later stage.
Also… why eliminate in a template all the other power PHP offers? You might be required to do something in it that an engine would not let you do, innit? I see no point.

  1. Template inheritance

It’s a cleaner, more reusable, more OO way to include common template code. It’s nice.

I’m not sure how this works yet. But I believe good coding achieves just that.

  1. Escape by default

<?php echo htmlspecialchars($var, ENT_QUOTES, ‘UTF-8’) ?>

  • vs -

{{ var }}

This is tremendously good for security. It’s the “secure by default” approach.

I’m not sure I buy into this either. If me and my application, (not the users) are the only ones in need to handle the templates, how does this pose a security concern?

Just some thoughts…

Hope everyone is having a nice holiday!

To me separating PHP and HTML is a huge advantage that I’d always go with, so I’ll use a templating engine even if its not smarty. Its just painful to my eyes whenever I see HTML file with lots of PHP tags, its fine for really simple ones with a few PHP tags for Table/Form’s default values but quickly become unreadable once there is a PHP if condition or foreach loop in the HTML file. I know some people may be comfortable with PHP embeded in HTML, but there are also half of the developers who completely hate it. In the end its the developers decision whether or not to use a template engine, I wont say either is right or wrong but both do exist for good reasons. So yeah you may not see it as an advantage to separate PHP from HTML, but for me it makes my development at least 2x faster and more enjoyable.

On the other hand PHP is indeed not a suitable templating language in the modern era, it did start as a templating language back in the 90s but nowadays it has evolved into more of a programming/scripting language than its original purpose. Again this may be personal opinion, but I am pretty sure I am not the only one who consider PHP an ugly templating language if used as one.

The bottom-line is that every coder/designer prefers a different style to write their code, there are benefits and issues that people weigh differently. Like I said before, you do not have to be convinced by the reasons to use a templating engine like smarty or twig, you are perfectly fine with or without it. There are some practices that are considered bad because there are insurmountable disadvantage/problems with them, one example I can give is global variables. There are also practices that are more of personal opinions/preferences, in these scenarios theres no right or wrong answer. Choose whatever suits you better and stick to it, thats what I believe a programmer is supposed to do for his/her application development.

Well, your code sample is actually a templating engine even if its a very simple one. But it’s important to distinguish between a templating engine and template language. It looks like you appreciate the former as it provides separation of concerns. However, your templates can use a variety of template languages like Smarty, Twig or plain PHP. If you use PHP then your templating engine can be very simple because PHP understands the language already. For other languages the templating engine needs to be much more elaborate because it needs to understand a foreign language.

What template language you use is up to your personal preference and there will be endless discussions on which one is better. Just choose which one you like best and you’ll be fine. Personally, I prefer a dedicated template language because I find PHP a bit clumsy and too verbose - in a template I want my main focus to be on HTML, not on the template language so I find it more readable to have short template syntax like Smarty. And it’s not only a matter of <?php echo $var ?> versus {$var} - template engines usually have many convenience functions or structures built in that help shorten the clutter, for example {html_options}, {cycle}, etc. - writing their equivalents in plain PHP takes many lines of code and I simply prefer not to do that if I don’t have to. I was using Smarty for some time and then for a small project I wanted to try out templates in PHP like in your example. All was fine but I really missed the simplicity and succinctness of Smarty syntax and I wished I didn’t have to type so much for such simple things. Yes, PHP is a templating language but a very primitive one and hasn’t been evolving in this respect at all.

Another big thing is template inheritance - if you’ve never tried it you can see a few short examples on the Smarty web site. This may not look like anything great but after some time I find this really helps organize things better than including files. PHP doesn’t have this built in so if you want to use inheritance you have to code it into your template engine. I prefer to use one that is already made by someone and that works well. AFAIK Twig also offers inheritance.

Apart from that template engines offer a lot more small convenient things that may not be that important but add up over time. Of course, there is a trade-off that you first have to learn a new template engine to get you going. But I suggest you first try to use a template engine with a dedicated template language for a small project and see how it goes - often it’s not easy to judge things before using them in real life.

Agree!

maybe I’m wrong and it’s just fear to the new
It is a small fear. I felt it and I also had a strange feeling about those “tags”.
After the first project it will look so natural :slight_smile:

There are few great features, like plugins (blocks, modifiers, functions) that may be used multiple times.

Even this does not look nice to you for now, you may also check some syntax_comparison aguments.

In the short example above, Smarty saved 110 characters, or a 36% syntax reduction. Also notice that Smarty takes care of boilerplate functions wherever it can, such as the empty() test in the above example. Smarty cleans up the syntax of templates, making them less fragile.

Thank you so much everyone for your answers, really enlightening and appreciated.

For the time being I find that Smarty slows me down because I’m still learning, but also because I might have to translate templates at some point, which then wouldn’t be portable to non-smarty projects and that I don’t like. Prefer to keep things with as less layers as possible. As you folks well say it’s a matter of preference.

Thanks,

Andres