Posted By

thermosilla on 01/04/09


Tagged

php templates


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

Jdub7
jeremyhcobb
NyX


PHP Template Function


 / Published in: PHP
 

Based on Jdub7's Pure PHP Template function

http://snipplr.com/view/10797/pure-php-template-function/

  1. <?php
  2.  
  3. function apply_template($file,$vars=array()){
  4.  
  5. $template = file_get_contents($file);
  6.  
  7. foreach ($vars as $key => $var)
  8. {
  9. $template = str_replace("[+$key+]", $var, $template);
  10. }
  11.  
  12. return $template;
  13. }
  14.  
  15. $template_vars = array(
  16. 'title' => 'Hello World!',
  17. 'text' => 'Hello!',
  18. 'link' => 'http://www.bigsmoke.us/php-templates/functions'
  19. );
  20.  
  21. $html = apply_template("_main.tpl",$template_vars);
  22. echo $html;
  23.  
  24. #_main.tpl
  25. #
  26. #
  27. #<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  28. # "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
  29. #<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" dir="ltr">
  30. #<head>
  31. # <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  32. # <title>[+title+]</title>
  33. #
  34. #</head>
  35. #<body>
  36. # <h1>[+title+]</h1>
  37. # <p>[+text+]</p>
  38. # <a href="[+link+]">[+link+]</a>
  39. #</body>
  40. #</html>
  41. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: Jdub7 on January 5, 2009

Interesting, I think this would be useful to offer my clients simple email templates. It poses some difficulty when using control structures.

Posted By: thermosilla on January 9, 2009

Yes, the idea behind the code is to use it to format simple documents without include php statements, like forms or database generated emails.

Thanks for your comments

You need to login to post a comment.