PHP 模板条件
<if a == 5 && b < 4>
one
<else>
<if a != 5>
two
<else>
<if a == 5 || $b == 5>
three
</if>
</if>
</if>
我如何从中获取一些变量:
[0] = "a == 5 && b < 4"
[1] = "one"
[2] = "a != 5"
[3] = "two"
[4] = "a == 5 || $b == 5"
[5] = "three"
或者您建议如何在模板中制定条件?
<if a == 5 && b < 4>
one
<else>
<if a != 5>
two
<else>
<if a == 5 || $b == 5>
three
</if>
</if>
</if>
How i can get from it a some variables:
[0] = "a == 5 && b < 4"
[1] = "one"
[2] = "a != 5"
[3] = "two"
[4] = "a == 5 || $b == 5"
[5] = "three"
Or how would you suggest to make conditions in the template?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,我并不反对模板系统,但为什么不使用纯 PHP 呢?
我没有看到在 PHP 内部痛苦地重建解析和求值逻辑有什么好处。
如果你真的需要这个,我会使用 Smarty。
I have nothing against templating systems in general, but why not use plain PHP for this?
I don't see the benefit of painfully rebuilding the parsing and evaluation logic inside PHP.
If you really need this, I would use Smarty.
一旦您开始向模板语言引入流程控制结构(if、loop...),您就无法通过对变量应用搜索和替换来简单地应用模板。您需要开始解析模板以提取依赖于条件的部分,并在需要时单独重新插入它们。
您最终可能要做的是应用一个初始解析步骤,将: 变为
:
然后,如果
a
为 true,您将应用模板temp
并将其存储到变量 <渲染模板main
时的 code>{temp-if-a}。如果a
为 false,则无需为{temp-if-a}
提供任何值。其他控制流结构可以使用此独立应用-替换序列来类似地实现,包括嵌套的序列(只需让您的模板应用程序算法递归地工作)。
As soon as you start introducing flow control constructs (if, loop... ) to your template language, you lose the ability to apply a template simply by applying a search-and-replace over your variables. You need to start parsing the template to extract the parts that are dependent on a condition, and re-insert them separately should the need happen.
What you will probably end up doing is apply an initial parsing step that turns:
Into:
Then, if
a
is true, you would apply templatetemp
and store it into variable{temp-if-a}
while rendering templatemain
. Ifa
is false, you would provide no value for{temp-if-a}
.The other control flow structures can be similarly implemented with this extract-apply independently-replace sequence, including nested ones (just have your template application algorithm work recursively).