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)
From stackoverflow
-
/** * 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); }
Emil H : Neat. :) It should be said that it's php 5.3+ only, though.alex : You'll need to be running PHP 5.3 to use this. Otherwise it is not so elegant.willell : Try to avoid this if you can. Regexes are resource-expensive.Gordon : Same as Fabien Potencier's in [Design patterns revisited with PHP 5.3](http://www.slideshare.net/fabpot/design-patternrevisitedphp53) (page 45)efritz : It's actually a method from the Symfony2 framework.Alex : 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).Gordon : @efritz figures because Fabien is the author of Symfony2 -
$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);
Gordon : 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)`
0 comments:
Post a Comment