Archive

Posts Tagged ‘Smarty’

Smarty parse a string as template

October 16th, 2009 Comments off

It’s the best way to parse a string as Smarty template. You need to follow only 3 steps!

First of all we need to register a new template resource – string.

$smarty->register_resource("string", array("string_get_template",
 "string_get_timestamp",
 "string_get_secure",
 "string_get_trusted"));

Then add function implementations

function string_get_template ($tpl_name, &$tpl_source, &$smarty_obj) {
    global $smartyStringTemplates;
    $tpl_source = $smartyStringTemplates[$tpl_name];
    return true;
}

function string_get_timestamp($tpl_name, &$tpl_timestamp, &$smarty_obj) {
    // do database call here to populate $tpl_timestamp.
    $tpl_timestamp = time;
    return true;
}

function string_get_secure($tpl_name, &$smarty_obj) {
    // assume all templates are secure
    return true;
}

function string_get_trusted($tpl_name, &$smarty_obj) {
    // not used for templates
}

And the last step. Create an array of string templates and parse a string by passing it’s index in array

$smartyStringTemplates = array('{php}date(){/php}', '{$helloWold}');

print $smarty->fetch("string:1"); // will fetch a string {$helloWold}
Categories: PHP Tags: ,