views:

74

answers:

2

Hi

does anyone know a php templating system that is very simple, something like almost as simple as str_replace("{variable}", $variable); ?

I need this for a series of textareas in the administration panel, where the site admin should change templates for various elements of the website (not complex stuff like pages etc, just blocks of content)

+2  A: 
/**
 * Renders a single line. Looks for {{ var }}
 *
 * @param string $string
 * @param array $parameters
 *
 * @return string
 */
function renderString($string, array $parameters)
{
    $replacer = function ($match) use ($parameters)
    {
        return isset($parameters[$match[1]]) ? $parameters[$match[1]] : $match[0];
    };

    return preg_replace_callback('/{{\s*(.+?)\s*}}/', $replacer, $string);
}
efritz
Neat. :) It should be said that it's php 5.3+ only, though.
Emil H
You'll need to be running PHP 5.3 to use this. Otherwise it is not so elegant.
alex
Try to avoid this if you can. Regexes are resource-expensive.
willell
Same as Fabien Potencier's in [Design patterns revisited with PHP 5.3](http://www.slideshare.net/fabpot/design-patternrevisitedphp53) (page 45)
Gordon
It's actually a method from the Symfony2 framework.
efritz
nice. is there a way to make this work for php 4 ?
Alex
@Alex You'll need to make a separate function for the callback (outside of the scope you are currently in).
alex
@efritz figures because Fabien is the author of Symfony2
Gordon
+1  A: 
$findReplaces = array(
    'first_name' => $user['first_name'],
    'greeting' => 'Good ' . (date('G') < 12 ) ? 'morning' : 'afternoon'
);

$finds = $replaces = array();

foreach($findReplaces as $find => $replace) {
    $finds[] = '{' . $find . '}';
    $replaces[] = $replace;
}

$content = str_replace($finds, $replaces, $content);
alex
why dont you just include the curly braces, e.g. `{{first_name}}` in the array keys and simply do `str_replace(array_keys($findReplaces),$findReplaces,$content)`
Gordon