模板系统中的 if 语句

发布于 2024-10-16 13:57:21 字数 147 浏览 10 评论 0原文

比方说,我如何解析 {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 技术交流群。

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

发布评论

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

评论(6

ペ泪落弦音 2024-10-23 13:57:21

请使用php。
只需放入您的 tpl 文件:

<?php if ($var > 2) .... ?> 

它比在 php 中解析文件要简单得多,代码更少,速度也快得多

Please use php.
Just put in your tpl file:

<?php if ($var > 2) .... ?> 

It's a lot simpler, less code and a lot faster than parsing the file in php

梦毁影碎の 2024-10-23 13:57:21

使用

<? if( condition ) :
    ....
    ....
else : 
    ....
    ....
endif; ?>

if () { } 和 if () 之间的区别:endif;

use

<? if( condition ) :
    ....
    ....
else : 
    ....
    ....
endif; ?>

Difference between if () { } and if () : endif;

习惯成性 2024-10-23 13:57:21

您已经得到了上一个问题的答案: if statements in php templates using tpl< /a>
但既然你不会离开,那么让我快速回答一下,然后指出哪些将是你的下一个绊脚石。

// 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
}

使用这样的正则表达式会跳过嵌套的 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.

// 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
}

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 just return $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.

時窥 2024-10-23 13:57:21

实际上,除非您需要嵌套 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);

Actually it's pretty simple unless you need nested if conditions.

$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);
油焖大侠 2024-10-23 13:57:21

您可以在模板文件(.tpl)中使用以下格式。,

{if $url == 'error'}
Error message Invalid Login!
{/if} 

You can use the following format into your template file(.tpl).,

{if $url == 'error'}
Error message Invalid Login!
{/if} 
夜未央樱花落 2024-10-23 13:57:21

有一个 php 代码示例解析以下模板(php 5.3+):

[IF {post_content}]Post content is filled![ENDIF]
[IF {post_content}]Post content is filled![ELSE]{post_content}[ENDIF]

代码:

$tags = array('post_content'=>'POST_CONTENT');

$message = '1: [IF {post_content}]Post content: {post_content}![ENDIF]
            2: [IF {post_content}]Post content is filled![ELSE]Post content is empty![ENDIF]';

$matches = array();

preg_match_all('/\[IF \{([^\}]*)\}\](.[^\]]+)(?:\[ELSE\](.+?))?\[ENDIF\]/s', $message, $matches);

if ( empty($matches) ) {
    return $message;
}

$math_tag = '';
foreach ( $matches[0] as $m_index => $match )
{
    $math_tag =  trim($matches[1][$m_index]);

    if ( !empty($tags[$math_tag]) ) {
        // IF value is not empty
        $message = str_replace($match, $matches[2][$m_index], $message);
    } elseif( empty($tags[$math_tag]) && $matches[3][$m_index] ) {
        // ELSE
        $message = str_replace($match, $matches[3][$m_index], $message);
    } else {
        // IF NO ELSE condition - REMOVE ALL
        $message = str_replace($match, '', $message);
    }
}

foreach($tags as $tag => $value)
   $message = str_replace('{'. $tag .'}', $value, $message);

echo $message;

There is an php code example that parses following temaplate (php 5.3+):

[IF {post_content}]Post content is filled![ENDIF]
[IF {post_content}]Post content is filled![ELSE]{post_content}[ENDIF]

Code:

$tags = array('post_content'=>'POST_CONTENT');

$message = '1: [IF {post_content}]Post content: {post_content}![ENDIF]
            2: [IF {post_content}]Post content is filled![ELSE]Post content is empty![ENDIF]';

$matches = array();

preg_match_all('/\[IF \{([^\}]*)\}\](.[^\]]+)(?:\[ELSE\](.+?))?\[ENDIF\]/s', $message, $matches);

if ( empty($matches) ) {
    return $message;
}

$math_tag = '';
foreach ( $matches[0] as $m_index => $match )
{
    $math_tag =  trim($matches[1][$m_index]);

    if ( !empty($tags[$math_tag]) ) {
        // IF value is not empty
        $message = str_replace($match, $matches[2][$m_index], $message);
    } elseif( empty($tags[$math_tag]) && $matches[3][$m_index] ) {
        // ELSE
        $message = str_replace($match, $matches[3][$m_index], $message);
    } else {
        // IF NO ELSE condition - REMOVE ALL
        $message = str_replace($match, '', $message);
    }
}

foreach($tags as $tag => $value)
   $message = str_replace('{'. $tag .'}', $value, $message);

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