Dirt-simple PHP templates… can this work without `eval`?

a 夏天 提交于 2019-11-27 12:27:55
Spudley

PHP was itself originally intended as a templating language (ie a simple method of allowing you to embed code inside HTML).

As you see from your own examples, it got too complicated to justify being used in this way most of the time, so good practice moved away from that to using it more as a traditional language, and only breaking out of the <?php ?> tags as little as possible.

The trouble was that people still wanted a templating language, so platforms like Smarty were invented. But if you look at them now, Smarty supports stuff like its own variables and foreach loops... and before long, Smarty templates start to have the same issues as PHP templates used to have; you may as well just have used native PHP in the first place.

What I'm trying to say here is that the ideals of a simple templating language aren't actually that easy to get right. It's virtually impossible to make it both simple enough not to scare off the designers and at the same time give it enough flexibility to actually do what you need it to do.

I'm gonna do something silly and suggest something that requires no templating engine at all and requires only at most 5 characters more per variable/call than what you have there - replace {$foo} with <?=$foo?> and then you can use include for all your templating needs

If all you need is variable replacement though this is a templating function i actually use:

function fillTemplate($tplName,$tplVars){
  $tpl=file_get_contents("tplDir/".$tplName);
  foreach($tplVars as $k=>$v){
    $tpl = preg_replace('/{'.preg_quote($k).'}/',$v,$tpl);
  }
  return $tpl;
}

if you want to be able to call functions or have loops, there is basicly no way around calling eval short of pre-processing.

If you don't wont to use a big template engines like Twig (which I sincerely recommend) you can still get good results with little code.

The basic idea that all the template engines share is to compile a template with friendly, easy-to-understand syntax to fast and cacheable PHP code. Normally they would accomplish this by parsing your source code and then compiling it. But even if you don't want to use something that complicated you can achieve good results using regular expressions.

So, basic idea:

function renderTemplate($templateName, $templateVars) {
    $templateLocation = 'tpl/'      . $templateName . '.php';
    $cacheLocation    = 'tplCache/' . $templateName . '.php';
    if (!file_exists($cacheLocation) || filemtime($cacheLocation) < filemtime($templateLocation)) {
        // compile template and save to cache location
    }

    // extract template variables ($templateVars['a'] => $a)
    extract($templateVars);

    // run template
    include 'tplCache/' . $templateName . '.php';
}

So basically we first compile the template and then execute it. Compilation is only done if either the cached template doesn't yet exist or there is a newer version of the template than the one in the cache.

So, let's talk about compiling. We will define two syntaxes: For output and for control structures. Output is always escaped by default. If you don't want to escape it you must mark it as "safe". This gives additional security. So, here an example of our syntax:

{% foreach ($posts as $post): }
    <h1>{ $post->name }</h1>
    <p>{ $post->body }</p>
    {!! $post->link }
{% endforeach; }

So, you use { something } to escape and echo something. You use {!! something} to directly echo something, without escaping it. And you use {% command } to execute some bit of PHP code without echoing it (for example for control structures).

So, here's the compilation code for that:

$code = file_get_contents($templateLocation);

$code = preg_replace('~\{\s*(.+?)\s*\}~', '<?php echo htmlspecialchars($1, ENT_QUOTES) ?>', $code);
$code = preg_replace('~\{!!\s*(.+?)\s*\}~', '<?php echo $1 ?>', $code);
$code = preg_replace('~\{%\s*(.+?)\s*\}~', '<?php $1 ?>', $code);

file_put_contents($cacheLocation, $code);

And that's it. You though have to note, that this is more error prone than a real template engine. But it will work for most cases. Furthermore note that this allows the writer of the template to execute arbitrary code. That's both a pro and a con.

So, here's the whole code:

function renderTemplate($templateName, $templateVars) {
    $templateLocation = 'tpl/'      . $templateName . '.php';
    $cacheLocation    = 'tplCache/' . $templateName . '.php';
    if (!file_exists($cacheLocation) || filemtime($cacheLocation) < filemtime($templateLocation)) {
        $code = file_get_contents($templateLocation);

        $code = preg_replace('~\{\s*(.+?)\s*\}~', '<?php echo htmlspecialchars($1, ENT_QUOTES) ?>', $code);
        $code = preg_replace('~\{!!\s*(.+?)\s*\}~', '<?php echo $1 ?>', $code);
        $code = preg_replace('~\{%\s*(.+?)\s*\}~', '<?php $1 ?>', $code);

        file_put_contents($cacheLocation, $code);
    }

    // extract template variables ($templateVars['a'] => $a)
    extract($templateVars, EXTR_SKIP);

    // run template
    include 'tplCache/' . $templateName . '.php';
}

I haven't tested the above code ;) It's only the basic idea.

There is no ultimate solution. Each has pros and cons. But you already concluded what you want. And it seems a very sensible direction. So I suggest you just find the most efficient way to achieve it.

You basically only need to enclose your documents in some heredoc syntactic sugar. At the start of each file:

<?=<<<EOF

And at the end of each template file:

EOF;
?>

Achievement award. But obviously this confuses most syntax highlighting engines. I could fix my text editor, it's open source. But Dreamweaver is a different thing. So the only useful option is to use a small pre-compiler script that can convert between templates with raw $varnames-HTML and Heredoc-enclosed Templates. It's a very basic regex and file rewriting approach:

#!/usr/bin/php -Cq
<?php
foreach (glob("*.tpl") as $fn) {
    $file = file_get_contents($fn);
    if (preg_match("/<\?.+<<</m")) {  // remove
        $file = preg_replace("/<\?(=|php\s+print)\s*<<<\s*EOF\s*|\s+EOF;\s*\?>\s*/m", "", $file);
    }
    else {   // add heredoc wrapper
        $file = "<?php print <<<EOF\n" . trim($file) . "\nEOF;\n?>";
    }
    file_put_contents($fn, $file);
}
?>

This is a given - somewhere you will need templates with a slight amount of if-else logic. For coherent handling you should therefore have all templates behave as proper PHP without special eval/regex handling wrapper. This allows you to easily switch between heredoc templates, but also have a few with normal <?php print output. Mix and match as appropriate, and the designers can work on the majority of files but avoid the few complex cases. For exampe for my templates I'm often using just:

include(template("index"));   // works for heredoc & normal php templ

No extra handler, and works for both common template types (raw php and smartyish html files). The only downside is the occasional use of said converter script.

I'd also add a extract(array_map("htmlspecialchars",get_defined_vars())); on top of each template for security.

Anyway, your passthrough method is exceptionally clever I have to say. I'd call the heredoc alias $php however, so $_ is still available for gettext.

<a href="calc.html">{$php(1+5+7*3)}</a> is more readable than Smarty

I think I'm going to adopt this trick myself.

<div>{$php(include(template($ifelse ? "if.tpl" : "else.tpl")))}</div>

Is stretching it a bit, but it seems after all possible to have simple logic in heredoc templates. Might lead to template-fileritis, yet helps enforcing a most simple template logic.

Offtopic: If the three <<<heredoc&EOF; syntax lines still appear too dirty, then the best no-eval option is using a regular expression based parser. I do not agree with the common myth that that's slower than native PHP. In fact I believe the PHP tokenizer and parser lag behind PCRE. Especially if it's solely about interpolating variables. It's just that the latter isn't APC/Zend-cached, you'd be on your own there.

Personally, I wouldn't touch with a stick any templating system where forgetting to escape a variable creates a remote code execution vulnerability.

Personally i'm using this template engine: http://articles.sitepoint.com/article/beyond-template-engine/5

I really like it a lot, especially because of it's simplicity. It's kinda similar to your latest incarnation, but IMHO a better approach than using heredoc and putting yet another layer of parsing above the PHP one. No eval() either, but output buffering, and scoped template variables, too. Use like this:

<?php   
require_once('template.php');   

// Create a template object for the outer template and set its variables.     
$tpl = new Template('./templates/');   
$tpl->set('title', 'User List');   

// Create a template object for the inner template and set its variables.
// The fetch_user_list() function simply returns an array of users.
$body = new Template('./templates/');   
$body->set('user_list', fetch_user_list());   

// Set the fetched template of the inner template to the 'body' variable
// in the outer template.
$tpl->set('body', $body->fetch('user_list.tpl.php'));   

// Echo the results.
echo $tpl->fetch('index.tpl.php');   
?>

The outter template would look like this:

<html>
  <head>
    <title><?=$title;?></title>
  </head>
  <body>
    <h2><?=$title;?></h2>
        <?=$body;?>
  </body>
</html>

and the inner one (goes inside the outter template's $body variable) like this:

<table>
   <tr>
       <th>Id</th>
       <th>Name</th>
       <th>Email</th>
       <th>Banned</th>
   </tr>
<? foreach($user_list as $user): ?>
   <tr>
       <td align="center"><?=$user['id'];?></td>
       <td><?=$user['name'];?></td>
       <td><a href="mailto:<?=$user['email'];?>"><?=$user['email'];?></a></td>
       <td align="center"><?=($user['banned'] ? 'X' : '&nbsp;');?></td>
   </tr>
<? endforeach; ?>
</table>

If you don't like / can't use short-tags then replace them with echos. That's as close to dirt-simple as you can get, while still having all the features you'll need IMHO.

Dead-simple templating using a function:

<?php

function template($color) {
        $template = <<< ENDTEMPLATE
The colors I like are {$color} and purple.
ENDTEMPLATE;

        return $template . "\n";
}

$color = 'blue';
echo template($color);

$color = 'turquoise';
echo template($color);

This outputs:

The colors I like are blue and purple.
The colors I like are turquoise and purple.

Nothing fancy, but it does work using standard PHP without extensions. Additionally, the use of functions to encapsulate the templates should help with proper MVC separation. Also (and this is what I needed for my coding today) I can save the filled-out template away for output to a file (later on in my program).

This is a minimal implementation of mustache to just substitute variables.

// Example:
//   miniMustache(
//      "{{documentName }} - pag {{ page.current }} / {{ page.total }}",
//      array(
//         'documentName' => 'YourCompany Homepage', 
//         'page' => array('current' => 1, 'total' => 10)
//      )
//    )
//    
// Render: "YourCompany Homepage - pag 1 / 10"

    function miniMustache($tmpl, $vars){
        return preg_replace_callback( '/\{\{([A-z0-9_\.\s]+)\}\}/',
            function ($matches) use ($vars) {
                //Remove white spaces and split by "."
                $var = explode('.',preg_replace('/[\s]/', '', $matches[1]));
                $value = $vars;
                foreach($var as $el){
                    $value = $value[$el];
                }
                return $value;
            }, 
            $tmpl);
    }

In some cases, it is more than enough. In case you need full power: https://github.com/bobthecow/mustache.php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!