Created
December 25, 2012 11:36
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
by using a closure you gain twice speed : https://gist.github.com/4427022