Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: simple template engine

Tags:

php

templates

I have a function called load_template()

this function has two parameters

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

the way I want this to work is.

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

<?php echo $title; ?>

then call

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

and have it fill it out.

how can I do this?


Output buffering method. I have come up with the code below.
I am sure 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;
}
like image 766
Hailwood Avatar asked Dec 16 '22 18:12

Hailwood


1 Answers

function load_template($name, $vars)
{
  extract($vars);
  include $name;
}

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

like image 91
Oswald Avatar answered Jan 08 '23 00:01

Oswald