1

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
  • if you any only streplace tempalte system, write it, this is few lines. Commented Oct 31, 2010 at 22:19
  • 1
    yes, but it's not very elegant. at least is there any way to map multiple variables to strings wrapped between { }, to avoid using 1000 str_replace's ? Commented Oct 31, 2010 at 22:20

2 Answers 2

2
/**
 * 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);
}
Sign up to request clarification or add additional context in comments.

6 Comments

Neat. :) It should be said that it's php 5.3+ only, though.
You'll need to be running PHP 5.3 to use this. Otherwise it is not so elegant.
Try to avoid this if you can. Regexes are resource-expensive.
Same as Fabien Potencier's in Design patterns revisited with PHP 5.3 (page 45)
@Alex You'll need to make a separate function for the callback (outside of the scope you are currently in).
|
2
$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);

4 Comments

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 Yep, that is much nicer. The only disadvantage I can see is that the delimiters need to be included which each search term - you know, the whole DRY thing.
yes, but then again, everyone using a template engine with curly braces over just using PHP deserves that :)
hehe, I will use that in my next project. no wait, I already do ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.