Spe*_*Wap 3 php templates templating templating-engine
我如何在我自己的模板类版本中解析,{if $var > 2}或者说{if $var}在.tpl文件中.我不想使用smarty,因为我不需要他们所有的插件.我只想要包含,if,for和foreachstatement.
Ant*_*oCS 13
请使用PHP.只需输入你的tpl文件:
<?php if ($var > 2) .... ?>
Run Code Online (Sandbox Code Playgroud)
它比在php中解析文件要简单得多,代码少,速度快得多
使用
<? if( condition ) :
....
....
else :
....
....
endif; ?>
Run Code Online (Sandbox Code Playgroud)
你已经得到了你的最后一个问题的答案:如果使用tpl的php模板中的语句
但是因为你不会消失,所以让我快速回答它,然后提到哪些是你的下一个绊脚石.
// handle {if}...{/if} blocks
$content =
preg_replace_callback('#\{if\s(.+?)}(.+?)\{/if}#s', "tmpl_if", $content);
function tmpl_if ($match) {
list($uu, $if, $inner_content) = $match;
// eval for the lazy!
$if = create_function("", "extract(\$GLOBALS['tvars']); return ($if);");
// a real templating engine would chain to other/central handlers
if ( $if() ) {
return $inner_content;
}
# else return empty content
}
Run Code Online (Sandbox Code Playgroud)
使用这样的正则表达式将跳过嵌套if.但你没有问过这个,所以我不会提到它.而作为在评论概述你实际上需要产业链的核心功能是(做进一步的替代{foreach}/ {include}/等),而不是只return $content为在这里.
这是可行的,但快速增长繁琐.这就是为什么所有其他模板引擎(你拒绝检查)实际上将.tpl文件转换为.php脚本.这更容易,因为PHP已经可以处理您试图模仿自己的模板类的所有控制结构.
实际上它非常简单,除非您需要嵌套if条件.
$template = '<b>{foo}</b>{if bar} lorem ipsum {bar}{/if}....';
$markers = array(
'foo' => 'hello',
'bar' => 'dolor sit amet',
);
// 1. replace all markers
foreach($markers as $marker => $value)
$template = str_replace('{'. $marker .'}', $value, $template);
//2. process if conditions
$template = preg_replace_callback('#\{if\s(.+?)}(.+?)\{/if}#s', function($matches) use ($markers) {
list($condition, $variable, $content) = $matches;
if(isset($markers[$variable]) && $markers[$variable]) {
// if the variable exists in the markers and is "truthy", return the content
return $content;
}
}, $template);
Run Code Online (Sandbox Code Playgroud)