Skip to content

Instantly share code, notes, and snippets.

@sukei
Last active August 24, 2021 12:05
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sukei/9092282 to your computer and use it in GitHub Desktop.
Save sukei/9092282 to your computer and use it in GitHub Desktop.
A Template Engine in a Tweet
<?php
/**
* The render function is a lightweight template engine, that allows string
* interpolation and output escaping.
*
* ...and it fits in a tweet.
*
* @author Quentin Schuler aka Sukei <qschuler@neosyne.com>
*/
function render($t,$a,$f='htmlentities') {
return preg_replace_callback('/\${(\w+)}/',function($m)use($a,$f){return @$f($a[$m[1]]);},$t);
}
@sukei
Copy link
Author

sukei commented Feb 19, 2014

<?php

$view = render('Hello ${name}!', [
    'name' => 'sukei',
]);

echo $view; // Hello sukei!
<?php

$view = render('Hello ${name}!', [
    'name' => '<strong>sukei</strong>',
]);

echo $view; // Hello &lt;strong&gt;sukei&lt;/strong&gt;!
<?php

$view = render('Hello <strong>${name}</strong>!', [
    'name' => 'sukei',
]);

echo $view; // Hello <strong>sukei</strong>!
<?php

$view = render('Hello ${name}!', [
    'name' => '<strong>sukei</strong>',
], 'strip_tags');

echo $view; // Hello sukei!
<?php

$view = render('Hello ${name}!', []);

echo $view; // Hello !
<?php

$view = render('Hello ${name}!', [
    'name' => '<strong>sukei & neosyne</strong>',
], function($string) {
    return htmlentities(strip_tags($string));
});

echo $view; // Hello sukei &amp; neosyne!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment