Altec Posted October 23, 2008 Share Posted October 23, 2008 Hey guys, A couple nights ago I found an article on how to write template engine in PHP. I followed the tutorial and am using it now in my scripts. However, as my scripts get more advanced, the more I realize I need to understand EXACTLY how the script is working and how to expand upon it. Here is my code: <?php class Page { var $page; function Page($template) { if(file_exists($template)) { $this->page = join('', file($template)); } else { die('Template file ' . $template . ' not found.'); } } function parse($file) { ob_start(); include($file); $buffer = ob_get_contents(); ob_end_clean(); return $buffer; } function replace_tags($tags = array()) { if(sizeof($tags) > 0) { foreach ($tags as $tag => $data) { $data = (file_exists($data)) ? $this->parse($data) : $data; $this->page = eregi_replace('{' . $tag . '}', $data, $this->page); } } else { die('No tags designated for replacement.'); } } function output() { echo $this->page; } } ?> Very very very simple. Obviously the pages can be created by: <?php $page = new Page('templates/index.html'); $page->replace_tags(array( 'PAGE_TITLE' => 'Post New Entry', 'MENU' => 'templates/menu.html', 'TITLE' => 'Post New Entry', 'CONTENT' => 'templates/sys/form.php', 'SIDEBAR' => 'templates/sidebar.html', 'FOOTER' => 'templates/footer.html', )); $page->output(); ?> However, I have hit a small snag... Can I nest it like so: <?php $page = new Page('templates/index.html'); $page->replace_tags(array( 'PAGE_TITLE' => 'Post New Entry', 'MENU' => 'templates/menu.html', 'TITLE' => 'Post New Entry', 'CONTENT' => $content = new Page('templates/main.html'); $content->replace_tags(array( 'MAIN' => 'Hi.', )); $content->output(); , 'SIDEBAR' => 'templates/sidebar.html', 'FOOTER' => 'templates/footer.html', )); $page->output(); ?> I'm afraid everything will blow up if I try to do that. Also, the tutorial I followed is about four (4) years old; are there any apparent security flaws or updates I can make? Thanks! Quote Link to comment Share on other sites More sharing options...
cerian Posted November 7, 2008 Share Posted November 7, 2008 i'm not quite sure if that will work, but i have been using the same tutorial as a base and have done the following. i 'm sure there is a better way, but it has worked for me on the small scale. <?php function there() { return "there"; } $content = "hello."; $content .= "out"; $content .= there(); $page->replacetags( array( 'content' = $content)) $page->output(); ?> hope this helps... Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.