PHP 模板条件

发布于 2024-10-01 21:16:32 字数 425 浏览 0 评论 0原文

<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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

如痴如狂 2024-10-08 21:16:32

一般来说,我并不反对模板系统,但为什么不使用纯 PHP 呢?

<?php if ($a == 5 && ($b < 4)): ?>
    one
<?php elseif ($a != 5): ?>
....

我没有看到在 PHP 内部痛苦地重建解析和求值逻辑有什么好处。

如果你真的需要这个,我会使用 Smarty。

I have nothing against templating systems in general, but why not use plain PHP for this?

<?php if ($a == 5 && ($b < 4)): ?>
    one
<?php elseif ($a != 5): ?>
....

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.

辞别 2024-10-08 21:16:32

一旦您开始向模板语言引入流程控制结构(if、loop...),您就无法通过对变量应用搜索和替换来简单地应用模板。您需要开始解析模板以提取依赖于条件的部分,并在需要时单独重新插入它们。

您最终可能要做的是应用一个初始解析步骤,将: 变为

Template "main" :  FOO <if a> BAR </if> QUX

Template "main" : FOO {temp-if-a} QUX
Template "temp" : BAR

然后,如果 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:

Template "main" :  FOO <if a> BAR </if> QUX

Into:

Template "main" : FOO {temp-if-a} QUX
Template "temp" : BAR

Then, if a is true, you would apply template temp and store it into variable {temp-if-a} while rendering template main. If a 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文