Php: simple template engine

I have a function called load_template()

this function has two parameters

  • $ name => template name
  • $ vars => array of key variables => to be replaced in the template.

how I want it to work.

in the template ('test') I want to be able to write

 <?php echo $title; ?> 

then call

 load_template('test', array('title' => 'My Title')); 

and fill it out.

How can i do this?


Output buffering method. I came up with the code below.
I am sure that it can be improved.
 public static function template($name, $vars = array()) { if (is_file(TEMPLATE_DIR . $name . '.php')) { ob_start(); extract($vars); require(TEMPLATE_DIR . $name . '.php'); $contents = ob_get_contents(); ob_end_clean(); return $contents; } throw new exception('Could not load template file \'' . $name . '\''); return false; } 
+4
source share
2 answers
 function load_template($name, $vars) { extract($vars); include $name; } 

Wrap ob_start and ob_get_clean if you want to capture the output in a variable.

+10
source

Something like that?

 function load_template($name, $vars) { include('template/'.$name.'.tpl'); //.tpl, .inc, .php, whatever floats your boat } 

and in template/whatever.tpl you will have:

 ... <title><?php echo $vars['title'] ?></title> ... ... <?php if (!empty($vars['content'])): //template still needs to know if the content is empty to display the div ?> <div id="content"> <?php echo $vars['content']; ?> </div> <?php endif; ?> ... 

Of course, it is assumed that the output is printed directly. You can print the tpl file directly or create a line or unload the output from the tpl file and return it from load_template

+2
source

Source: https://habr.com/ru/post/1336380/


All Articles