how to use Smarty better with PHP?

nonopolarity picture nonopolarity · May 17, 2009 · Viewed 9.5k times · Source

I found that using Smarty with PHP, sometimes extra time will need to be used for

1) using quite different syntax than PHP itself
2) need to check small cases, because documentation doesn't give finer details, such as for "escape"

http://www.smarty.net/manual/en/language.modifier.escape.php

it doesn't say escape:"quotes" is for double quotes only or for single quotes as well, so you need to write code to test it. Also for the case of escape:"javascript" -- can't tell exactly what and how it is escaped.

3) for something complicated, need to write helper functions or modifiers, so it needs a creation of new files and ending up doing it in PHP again.

by the way, does using Smarty provide a good speed up over use PHP alone? thanks.

Answer

Noah Goodrich picture Noah Goodrich · May 17, 2009

First, PHP is a templating language. Keep that in mind when you talk about using a template system for your PHP-based web applications.

The only 'real' argument that I've ever heard for using ANY templating engine was that they provide a simpler language for template manipulation which can be handy if you have template designers who don't know PHP and whom you don't trust to learn to use PHP judiciously.

Regarding these arguments, I would argue that if your template designers are not competent to learn enough PHP for template design, you should probably consider finding new template designers. Additionally, PHP itself provides a different syntax for control statements that you might use in a template versus in code. For example:

<? foreach($array as $key => $val): ?>
    <?= $val ?>
<? endforeach; ?>

VS:

<?php
    foreach($array as $key => $val) {
        echo $val;
    }

?>

Personally, I believe that templating engines arose in PHP because:

  1. That's way that other languages do it
  2. Better PHP programmers realized that they needed a way to enforce separation between presentation and application logic and templates were an easy way to do this.

The first reason is just kinda silly. The second reason can be overcome with a little self-control and even a rudimentary understanding of the necessity of separating layers in an application. The MVC design pattern is one way of approaching this problem. As far as exercising some self-control, my rule is that only necessary loops and if statements get used as well as functions that filter, escape, format the output for the screen.

Having used Smarty extensively, I can honestly say that it always presented me with more hurdles to get over than it did solutions. If anything, switching to PHP-based templates is what has actually decreased development time for both templates and code.