模板系统中的 if 语句
比方说,我如何解析 {if $var >; 2}
或 {if $var}
在我自己版本的模板类的 .tpl 文件中。我不想使用 smarty,因为我不需要他们所有的插件。我只想包含、if、for 和 foreach 语句。
How can I parse, let's say, {if $var > 2}
or {if $var}
in a .tpl file in my own version of a templating class. I do not wanna use smarty as I don't need all their plugins. I just want include, if, for and foreach
statements.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
请使用php。
只需放入您的 tpl 文件:
它比在 php 中解析文件要简单得多,代码更少,速度也快得多
Please use php.
Just put in your tpl file:
It's a lot simpler, less code and a lot faster than parsing the file in php
使用
if () { } 和 if () 之间的区别:endif;
use
Difference between if () { } and if () : endif;
您已经得到了上一个问题的答案: if statements in php templates using tpl< /a>
但既然你不会离开,那么让我快速回答一下,然后指出哪些将是你的下一个绊脚石。
使用这样的正则表达式会跳过嵌套的
if
。不过你没问过,所以我就不提了。正如评论中所述,您实际上需要链接到一个执行进一步替换的中心函数({foreach}
/{include}
/ 等),而不仅仅是 <代码>返回$内容,如下所示。这是可行的,但很快就会变得很麻烦。这就是为什么所有其他模板引擎(您拒绝检查)实际上将
.tpl
文件转换为.php
脚本。这要容易得多,因为 PHP 已经可以处理您尝试使用您自己的模板类来模仿的所有控制结构。You already got the answer with your last question: if statements in php templates using tpl
But since you won't go away otherwise, let me quickly answer it and then mention which will be your certain next stumbling blocks.
Using a regular expression like this will trip over a nested
if
. But you didn't ask about that, so I won't mention it. And as outlined in the comment you would actually need to chain to a central function that does further replacements ({foreach}
/{include}
/ etc.) instead of justreturn $content
as here.This is doable, but quickly growing cumbersome. And this is why all other templating engines (which you refuse to check out) actually convert
.tpl
files into.php
scripts. That's much easier because PHP can already handle all those control structures that you try to mimick with your own templating class.实际上,除非您需要嵌套 if 条件,否则它非常简单。
Actually it's pretty simple unless you need nested if conditions.
您可以在模板文件(.tpl)中使用以下格式。,
You can use the following format into your template file(.tpl).,
有一个 php 代码示例解析以下模板(php 5.3+):
代码:
There is an php code example that parses following temaplate (php 5.3+):
Code: