I'm currently writing a template engine. It even supports multiple "format"s. Currently it can parse .php
files and .tpl
(specific to this engine).
I'll give you a little example of both, just to give you an Idea.
template.php:
Name: <?php echo $this->h($name) ?>
Posts:
<?php foreach($posts as $post): ?>
- <?php echo $this->h($post->name) ?> (<?php echo count($post->comments) ?> comments)
<?php echo $this->render('post/shortpost', array('post' => $post)) ?>
<?php endforeach ?>
This is basicly just a standard PHP.
template.tpl
Name: {>$name}
Posts:
{foreach($posts as $post):}
- {>$post->name} ({=count($post->comments)} comments)
{=:render('post/shortpost', array('post' => $post))}
{endforeach}
This templating "language" simply gets translated into PHP above.
Currently these template's are parsed using eval()
.
Pro
Contra
I recently read about stream wrappers in php. You even could create your own. A other solution than eval
would be to create a custom stream wrapper for every template "format" and use include to parse the template.
This has the following (potential) flaws:
Pro
Contra
allow_url_(fopen|include)
has to be on? eval()
slow too?) A third option would to to parse the template to PHP code and cache them (as suggested by @Jen-YaKovalev).
Pro
Contra
tmp/
directory to save the parsed files. You need write permissions for PHP/webserver. Would be more insecure because hackers would append some malicious code easier. lately found the following php.net pages:
php://filter:
http://php.net/manual/en/wrappers.php.php strea_filter_register
http://fr2.php.net/manual/en/function.stream-filter-register.php This would be an other possibility to solve this problem. Using include('php://filter/read=filtername/resource=file.php')
, I could include a file which would first go through the filter filtername
, before it gets executed.
Pro
Contra
I think it's just a taste of one's coding-style, you'd better vote it or something.
(*) In an earlier project we used a 1-line code (an empty class-extension) in a data-url wrapped include, and its performance was awful.
您当然不希望在生产环境中的每个请求上解析模板,这将浪费资源,因此是一种缓慢而不是非常智能的方法,因此我强烈建议使用缓存的解析文件并包含( )方法。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.