Skip to content

Instantly share code, notes, and snippets.

@nrutman
Created December 25, 2012 11:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nrutman/4372785 to your computer and use it in GitHub Desktop.
Save nrutman/4372785 to your computer and use it in GitHub Desktop.
An easy templating (string / data merging) solution for PHP...for when a library is too much and the baked-in functions don't give you enough DRY. The example I needed replacement for is in the comment below.
<?php
function renderTemplate($template, $data) {
$pad_keys = create_function('$key', 'return "%" . $key . "%";');
$data_keys = array_map($pad_keys, array_keys($data));
$data_values = array_values($data);
return str_replace($data_keys, $data_values, $template);
}
/*
USAGE:
$template = '<%tag% %attr% class="poster pos-%pos% %type%"><img src="%img_url%" alt="%desc%"/><span class="screen"></span></%tag%>';
foreach($posters as $i => $poster) {
$t_data = array(
'tag' => ($poster->link) ? 'a' : 'span',
'attr' => ($poster->link) ? 'href="' . $poster->link . '" target="_blank"' : '',
'pos' => $i,
'type' => ($i == 1) ? 'featured' : '',
'img_url' => ($i == 1) ? $poster->fields['image']['sizes']['poster'] : $poster->fields['image']['sizes']['poster-small'],
'desc' => $poster->description
);
echo renderTemplate($template, $t_data);
endforeach
*/
@ichiriac
Copy link

ichiriac commented Jan 1, 2013

by using a closure you gain twice speed : https://gist.github.com/4427022

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