Pro's and cons of template engine?

Hi guys,

For my Yii2 development I use PHP as template language. However, i noticed that Yii2 also supports Smarty and Twig.

I am wondering what would be the (dis)advantage of using one of these template engines. I personally don’t see the need to use them and wonder if external plugins work with these template engines But I am curious what you guys think about it.

Why would you use it of prefer not to?

In my opinion template engine its unnecessary and I don’t like it.

I am thinking to use template engine but dont see the benefits of doing so. Would anyone elaborate why Yii2 developers should use template engine ?

Why add another layer of complexity to an already complex application?

HTML/CSS/PHP/Javascript is dead simple…

With a template engine you still need to know all of these PLUS the template language.

I’m sure also that there is a performance hit.

I agree personally. Don’t see the need of an extra layer of complexity. Though still curious why others would choose for it.

There are absolutely valid use cases for templating languages. In some applications, advanced users (Content Managers, Webmasters) must be allowed to edit some templates (emails for example, or even page templates) but must not be allowed to write and run arbitrary PHP code because they would quickly find very "creative" ways to bypass security protection and introduce bugs.

In fact, Yii has (and can have) only partial support for Smarty and Twig. The problem is that they aren’t just template languages but also template rendering engines. There’s a large overlap between their functionality and Yii’s built-in view resolving/rendering mechanism and you are likely to end up with a “worst of both worlds” result. I wouldn’t use any templating language in Yii apps unless it’s absolutely necessary. (like the use case mentioned above).

There are ways to do this, still only using PHP. Sorry I cannot point you to an example, however I did discuss it with another osCommerce Senior Team Member Mark Evans way back, who had deployed such a thing on something else he was working on.

Template engine are an inheritance of old times.

At certain point dynamic language got more and more complex and html and css as well.

Developing web application started to be more complicated as people getting more specialized in programming produce poor looking layout…

On the other end people that were specializing in layout produce poor server side programming.

In the middle of both sided relied integration of static template making them dynamic doing it in team work with different specialization.

In order to let web designer to finish the template without much effort on developer side smarty and other template engine came out.

Template engine provide simple programming statement that can be easily used by web designer to make their static html dynamic without big involvement of server side developer.

But now we got step further and on server side framework make think much easier for front side (widget creating the html code for you and including all css and javascrip needed in a simple way) and on the other end css framework allow also people that has small knowledge of css to make nice looking site with small effort.

So, unless of special layout needs, now a project do not require anymore web designer (at least do not require a specific person dedicated to this) in the developing team.

But also in complex layout web designer (usually external) are asked to provide a skeleton template which use specific technology (ie bootstrap) and is made dynamic by the server side developer.

In the end template engine are obsolete (or to be more precise not useful anymore), sure they evolved providing caching mechanism, code reusing, template decoupling etc etc but all of these are instrument that any recent server side framework provide in much more efficient way.

In my experience with Laravel blade, there are two major disadvantages

1 - Finding errors is unnecessarily difficult. Because the templates have to be compiled into external files, you’ll get a useless error message like FatalErrorException in fd67a8e5a7f14b74074d62c19c89385b line 47:

2 - No debugging. Similar to the first, you can’t use xdebug/breakpoints when the php code goes through the compiled files instead of the .php file

I find that using a template engine is cleaner.

This is a regular php view:




<?php

use yii\helpers\Html;

use yii\bootstrap\ActiveForm;


/* @var $this yii\web\View */

/* @var $form yii\bootstrap\ActiveForm */

/* @var $model \common\models\LoginForm */


$this->title = 'Login | Bugitor Admin';

$this->params['breadcrumbs'][] = $this->title;

?>

<div class="site-login">

	<h1>Login</h1>


	<p>Please fill out the following fields to login:</p>


	<div class="row">

    	<div class="col-lg-5">

        	<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>

            	<?= $form->field($model, 'username') ?>

            	<?= $form->field($model, 'password')->passwordInput() ?>

            	<?= $form->field($model, 'rememberMe')->checkbox() ?>

            	<div class="form-group">

                	<?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>

            	</div>

        	<?php ActiveForm::end(); ?>

    	</div>

	</div>

</div>



This is the Twig equivalent:


{{ use('yii/helpers/Html')}}

{{ use('yii/bootstrap/ActiveForm')}}

{{ set(this, 'title', 'Login') }}

{{ set(this, 'params', { 'breadcrumbs' : { '' : this.title } }) }}

<div class="site-login">

	<h1>{{this.title}}</h1>


	<p>Please fill out the following fields to login:</p>


	<div class="row">

    	<div class="col-lg-5">

        	{% set form = active_form_begin({'id' : 'login-form',}) %}

        	{{ form.field(model, 'username') | raw }}

        	{{ form.field(model, 'password').passwordInput() | raw }}

        	{{ form.field(model, 'rememberMe').checkBox() | raw }}

            	<div style="color:#999;margin:1em 0">

                	If you forgot your password you can <a href="{{ url('site/request-password-reset')}}">reset it</a>.

            	</div>

            	<div class="form-group">

                	{{ html.submitButton('Login', {'class': 'btn btn-primary',}) | raw }}

            	</div>

        	{{ active_form_end() }}

    	</div>

	</div>

</div>



I have configured Yii to make Twig handle .html files so that I can use every html-aware tool.

I think it is cleaner, and in most cases there is less to type.

And it is easier to resist putting too much logic in my views.

And Twig is awesome :)

If you think it is a problem when debugging, you are probably having code in your views that shouldn’t be there…

<edit>

However, because Twig compiles to plain and clean PHP, it isn’t much of a problem to debug. Especially not when Twig debugging is turned on.

</edit>

As I wrote the only reason to use template engine is that you have web designer actively involved in the project. And this mean also that the web designer should know how to use the template engine…

Template engine add overhead to execution time, cpu, and memory. If you do a search on google you will see that the main reason (if not the only one) in the end to adopt a template engine is to allow web designer to operate in autonomy in modifying views.

this code look mostly like a search and replace of <?= with {{

In my opinion this example do not add anything to standard yii2 php template…

Any php editor handle html inside php page, most of html editor handle html code in file with different extension or language…

If you get an exception in view it is not necessarily because you have logic in view:

you access an active record propertied that does not exist, mistyping the field name, wrong access to related data …)

you try to use a widget with wrong namespace, passing wrong parameter…

you try to access to a variable that does not exist, forgot to pass it to the view, name mistyping

if you want I can go on with exception that can arise in a view which are not logic related…

In my opinion it is a bad idea to apply a technology when you don’t really need it.

Just think to one of the main criticism that often are moved to yii: it heavily use array for configuration and consequently configuration is hard to read (which in reality mean not elegant)

Others framework use xml, yalm, json or whatever which in the end get converted to an array… So you use something else (which revert to an array) so you look more smart but adding cpu and memory overhead to page execution… are you sure you are smart?

You are not changing configuration everyday, as well as you do not need to change view everyday, mostly you operate on the logic.

I agree with Roberto Braga. He explains really well why it has no advantage over using it.

I don’t use Twig because I want ‘dumb’ designers to be able to edit them, but because I prefer to use the right tool for the right job.

Symfony says that using Twig as templating engine is a best practice, and they say:

And then:

I tried Smarty a couple of years ago, and I did not like it. It was slow and offered no benefits over plain old PHP, and from what I hear, it is still slow.

However, Twig is a different beast.

Here is the blog post that Fabien Potencier wrote when he launched the Twig project: http://fabien.potenc…nes-in-php.html

In that post, he lists some performance numbers:




Library Time (sec) Memory (Ko) Templates rendered per second

Twig                        3 		1,190    	3,333 

PHPTAL 				3.8  	2,100    	2,632 

Dwoo     				6.9  	1,870    	1,449 

Smarty 2 			12.9   	2,350   		775 

Smarty 3 			14.9   	3,230   		671 

Calypso          	34.3      	620   		292 

eZ Templates    53      	5,850   		189



It would be interesting to see some numbers that are more recent…

Twig is not really difficult to learn, the docs are a couple of pages long, and it is flexible by means of filters and functions and macros.

I don’t want to be without it.

Because of DRY and separation of concerns, but also because I use Twig with most of my other web projects.

Each to his own, of course.

However, this topic is about Pros and Cons of template engines.

The right tool is the one you need. According to template engine developer (see the following links), twig smarty and whatever are addressed to web designer, are you a web designer that does not understand php?

Asking Fabien if twig is good is like asking the butcher if the meat is good.

This post blog is ancient, it is back to 2009… he still speak of php4, he say that twig is good because it use php5.

Saying that use of template is just best practice is not enough, you must say why. Then you can decide if using it is your case.

If I say that table is the best for page layout, do you believe me or you want to know why?

Try to look on the internet for reason to use template system:

http://www.schibsted…r-your-webpage/

  • Point 1,2,4,6,7 are about collaboration with web designer
  • Point 3 is about caching and server side framework usually are much better at this
  • Point 5, filters and other stuff… well server side framework already do this

This is from smarty site http://www.smarty.net/why_use

Dwoo site http://dwoo.org/faq/

And this article is interesting too https://dzone.com/ar...ns-php-template

If you want I can go further and search more resource…

Just to give you an idea… In my company we have graphic designer (not web designer) whose does not know html (I know it is odd and I would fire all of them if I could). They do the graphics and we implement it… Using a template engine would add something to the teamwork? NO

About benchmark it is very hard to find recent data and almost impossible to find something that compare with php:

http://dwoo.org/benchmark/loop/ (it has also php in the list but it is still old)

https://github.com/f...en/benchmark.md (2014)

https://github.com/t...wig/issues/1089 (2013)

Didn’t include anything older that 2013.

I think that you can search as much as you want but it would be very difficult to find some benchmark that compare with plane php.

Using Twig is Symfony best practice, right now, in 2015.

Simply because people prefer using it over php: http://symfony.com/blog/new-in-symfony-2-7-twig-as-a-first-class-citizen

There are lots of wildly talented people who use Twig, so I consider myself in very good company.

I personally find that my views are cleaner and more elegantly written in Twig.

But, if php works for you, fine. :)

I know this nasty system pupular in add agencies. This is the completely oddest way of interface design: these people unaware of HTML/CSS deliver their creations as if the developer was obliged to re-invent all standard elements from scratch simply because "I would like the drop-down to expand to the left rather than downwards" or so…

I said - no, thank you - never ever back again to web development. I focused on apps where productivity not design is priority!

And indeed - I had similar discussion recently and were told by Symfony developer Twig is passe and only used by these "design" people, so nobody bother to Twig unless very large-scale project is concerned and design is managed by separate department.

I use Twig because I want to cut down on visual noise and because I like the idea of separation of concerns.

Not because I don’t know how to program :)

<edit>

@Ziggy: That Symfony developer you mentioned obviously didn’t read the announcement I linked to earlier about Symfony making Twig the default view renderer.

</edit>

sorry I tough this was yii forum not Symfony one… :lol:, pass me the joke

You still didn’t answer me: why is best practice?

You keep to point me to Fabien posts, the butcher always says it is good… and does not explain why!

He says that most Symfony developer use twig… How does he know this? Ziggi spoked with a Symfony developer whose said the contrary…

Did you read the part in which he speak about twig overhead in Symfony?

This is because he tightly integrated twig in 2.7 version of the framework (you must use it unless you load an external plugin to use something else). Can you imagine how much overhead a template engine add to a page rendering?

My impression is that Fabien has a personal view (is not the point if it is correct or not) and he push it at any costs.

Looking at Symfony I have the impression that in a way or another in the end is Fabien word that count. Which is correct in a way: even if it is a open source product it is still a SesnsioLab product which is Fabien company.

Fortunately here things are bit more participative (thats one of the reason I like yii).

I pointed you to an article which is as well of 2015, and to the website of template engine (which are up to date since these projects are still alive) that state clearly that this tool is useful only if in the project are involved web designer.

Please note that I didn’t post article that say php is better than template, I just looked for reason to use template.

I keep asking why is best practice and why I should use it because probably I’m totally wrong and it is really better.

My problem is that until now I didn’t find any good reason to use a template engine, and believe me I know them and used them and still use time to time.

I do not say that I will never use template engine I’m only say that I will use them when the necessity of the project will require it (i.e. when in the teamwork there is one or more web designer).

I am revisiting this topic :)

Yes, I probably would agree that a template engine like Twig is probably not a good match for Yii applications.

However, I have come across MtHaml (Multi-target HAML) for which there is a Yii2 extension, and I like it!

It allows me to write HTML like you do with Emmet, but the source code is not expanded (of course).

Here is an example:




-use yii\helpers\Html

-use yii\bootstrap\ActiveForm

-$view->title = 'Login'

-$view->params['breadcrumbs'][] = $view->title;

.site-login

  %h1 #{$view->title}

  %p Please fill out the following fields to login:

  .row

	.col-lg-5

  	-$form = ActiveForm::begin(['id' => 'login-form'])

  	!=$form->field($model, 'username')

  	!=$form->field($model, 'password')->passwordInput()

  	!=$form->field($model, 'rememberMe')->checkbox()

  	.form-group

    	!=Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button'])

  	-ActiveForm::end()



Does it not look clean?

And we get to keep our php in our views…

This is the Yii version:


<?php

use yii\helpers\Html;

use yii\bootstrap\ActiveForm;

$this->title = 'Login | Bugitor Admin';

$this->params['breadcrumbs'][] = $this->title;

?>

<div class="site-login">

	<h1>Login</h1>

	<p>Please fill out the following fields to login:</p>

	<div class="row">

    	<div class="col-lg-5">

        	<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>

            	<?= $form->field($model, 'username') ?>

            	<?= $form->field($model, 'password')->passwordInput() ?>

            	<?= $form->field($model, 'rememberMe')->checkbox() ?>

            	<div class="form-group">

                	<?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>

            	</div>

        	<?php ActiveForm::end(); ?>

    	</div>

	</div>

</div>



I know which one I like better :)

PS: sorry about the awful formatting.

The haml version is of course only indented four spaces after the .row

This is the login form version from yesterday when I still used Twig:


{{ use('yii/helpers/Html')}}

{{ use('yii/bootstrap/ActiveForm')}}

{{ set(this, 'title', 'Login') }}

{{ set(this, 'params', { 'breadcrumbs' : { '' : this.title } }) }}

<div class="site-login">

	<h1>{{this.title}}</h1>

	<p>Please fill out the following fields to login:</p>

	<div class="row">

    	<div class="col-lg-5">

        	{% set form = active_form_begin({'id' : 'login-form',}) %}

        	{{ form.field(model, 'username') | raw }}

        	{{ form.field(model, 'password').passwordInput() | raw }}

        	{{ form.field(model, 'rememberMe').checkBox() | raw }}

            	<div style="color:#999;margin:1em 0">

                	If you forgot your password you can <a href="{{ url('site/request-password-reset')}}">reset it</a>.

            	</div>

            	<div class="form-group">

                	{{ html.submitButton('Login', {'class': 'btn btn-primary', 'id': 'login-button'}) | raw }}

            	</div>

        	{{ active_form_end() }}

    	</div>

	</div>

</div>



As you can see, it is not especially useful. It doesn’t make my views any cleaner…

However, my new MtHaml powered templates does. :lol:

See previous post ^