Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PHP inside Smarty template files [duplicate]

Tags:

php

smarty

The use of PHP inside Smarty template files has been possible in previous versions of Smarty but is now deprecated.

You can however still do it by using a backwards compatibility wrapper.

This makes using PHP from inside a template file possible by doing:

{php}echo "Hello World";{/php}

Does anyone know of any problems or issues this might cause?

like image 424
Barney Avatar asked Jan 19 '26 21:01

Barney


1 Answers

To expand the comments already given into a full answer, the problem with embedding arbitrary PHP code is that it breaks down the separation between PHP and Smarty.

Since Smarty compiles directly to PHP, everything you write in Smarty can be written in pure PHP, and may or may not end up just as readable, e.g.

  • <?= $foo ?> for {$foo} is fine
  • <?php if ( $expr ): ?> Hello <?php endif; ?> for {if $expr} Hello {/if} is not too bad either
  • but <?= htmlspecialchars(strtoupper($foo ?: 'Hello')); ?> for {$foo|default:'Hello'|upper|escape:html} is a bit harder on the eye

The main advantages I see of using Smarty (all of which are basically voided if you use {php}):

  • Obvious separation - it is always clear that a given file is considered a Template, because it's in Smarty. Conversely, it is always clear that output directly within a PHP function is wrong, because the result should be being passed to the template.
  • Forced separation - application logic such as database connectivity or input validation cannot "leak" into your View layer if you don't allow those functions to be called from Smarty templates
  • Security - you can give non-trusted front-end developers / designers access to Smarty templates and tightly control the data and functionality they have access to.

The only benefit you'd retain if you mixed Smarty and PHP would be those parts of Smarty syntax which are more readable than their PHP equivalent, like the modifier example I showed above.

like image 143
IMSoP Avatar answered Jan 22 '26 10:01

IMSoP