Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

super-light templating system in PHP that doesn't allow php code inside templates or use eval

I'm searching for a very basic PHP templating system. Right now I'm using:

/**
 * Renders a single line. Looks for {{ var }}
 *
 * @param string $string
 * @param array $parameters
 *
 * @return string
 */
function renderString($string, array $parameters)
{
    $replacer = function ($match) use ($parameters)
    {
        return isset($parameters[$match[1]]) ? $parameters[$match[1]] : $match[0];
    };

    return preg_replace_callback('/{{\s*(.+?)\s*}}/', $replacer, $string);
}

(from here: PHP - Extremely light templating system)

but I can only assign and display variables. I also need a way to use conditions like IF and loop arrays.

I found Rain TPL - http://www.raintpl.com/Quick-Start/#if - which is very close to what I'm looking for, but there are a few things that I don't like it it:

  • it allows the dude who is writing the template to run PHP functions (inside the IF condition).
  • it writes cache and php files, which I don't want

So, is there anything out there similar to this, but even more "basic", strict, and more secure?

like image 758
Alex Avatar asked Apr 24 '11 07:04

Alex


People also ask

Is PHP a templating language?

He wasn't opposed to using C to handle back-end business logic but wanted a better way to generate dynamic HTML for the front end. PHP was originally designed as a templating language, but adopted more features over time and eventually became a full programming language in its own right.

How do you use templates in PHP explain?

A PHP template engine is a way of outputting PHP in your HTML without using PHP syntax or PHP tags. It's supposed to be used by having a PHP class that will send your HTML the variables you want to display, and the HTML simply displays this data.


1 Answers

Twig might be for you.

It can do conditions, and has a sandbox mode for untrusted code.

It does compilation and caching, but that seems to be possible to turn off.

like image 59
Pekka Avatar answered Oct 10 '22 23:10

Pekka