I am building a very lightweight framework and would like a custom template parser. I of course know about other solutions such as Smarty, however that is much overkill for what I need.
I've built simple template parsers before but never figured out how to use loops. I am thinking something on the idea of Smarty's foreach loops, or maybe phpBB's loop blocks. Unfortunately I don't really have time right now to paw through those applicati开发者_运维技巧ons, so what is the simplest way to implement loops into a template parser?
It must be able to handle multi-dimensional arrays as well.
go for phpkerby I think that would be solution to your problem
PHP KIRBY
Here's the general idea of how to do it...
You need to set up your loop start and ending parameters. So something like:
{LOOP_START:users}
<p>{name}</p>
{LOOP_END:users}
Then in your template code, you want to grab the loop placeholder from {LOOP_START:users}
to {LOOP_END:users}
. You also want to grab a snippet of everything between those tags. Loop through your array and replace the vars in the snippet, then replace the whole placeholder with your new output. Here's the basic idea:
$output = your_method_to_get_the_full_template_contents();
$loop_with_tags = your_method_to_find_the_loop_tags_and_content($output, 'users');
$loop_inside_tags = your_method_to_get_the_loop_contents($loop_with_tags);
$loop_output = '';
foreach($users as $user) {
$loop_output .= str_replace(array_keys($user), array_values($user), $loop_inside_tags);
}
$output = str_replace($loop_with_tags, $loop_output, $output);
精彩评论