2010/07/09

Small php script in Smarty templates

Sometimes, we wanted to run a small PHP scripts inside Smarty templates. That’s good that we don’t need to touch PHP source file to add smarty variables. Here is an example,

In the PHP source code, I have smarty variable named phpvar,

<?php
$phpvar = "Hello World";
$smarty->assign('phpvar', $phpvar);
?>

And in the smarty tempate file, I wanted to split phpvar into tow variable. Sure, you can update source code, to include 2 variables, but sometime, you may do it in the template file. Here is how,

{if preg_match("/(.+)\s+(.+)/", $phpvar, $matches)}
<li>{$matches.1}</li>
<li>{$matches.2}</li>
{/if}