3

たとえば、自分のバージョンのテンプレート クラスの .tpl ファイルを解析するにはどうすればよいでしょう{if $var > 2}か。{if $var}私はすべてのプラグインを必要としないので、smarty を使用したくありません。インクルード、if、for、およびforeachステートメントが必要なだけです。

4

6 に答える 6

13

php を使用してください。あなたのtplファイルに入れるだけです:

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

PHPでファイルを解析するよりもはるかに簡単で、コードが少なく、はるかに高速です

于 2011-02-09T13:35:02.263 に答える
9

使用する

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

if(){}とif()の違い:endif;

于 2011-02-17T04:43:48.823 に答える
6

最後の質問: tpl を使用した php テンプレートの if ステートメントで
既に答えを得てい ます。

// 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}return $content

これは実行可能ですが、急速に面倒になります。これが、他のすべてのテンプレート エンジン (チェックアウトを拒否する) が実際に.tplファイルを.phpスクリプトに変換する理由です。PHP は、独自のテンプレート クラスで模倣しようとするすべての制御構造を既に処理できるため、はるかに簡単です。

于 2011-02-16T22:35:59.873 に答える
5

ネストされた 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);
于 2015-02-03T09:28:46.830 に答える
0

テンプレート ファイル (.tpl) には次の形式を使用できます。

{if $url == 'error'}
Error message Invalid Login!
{/if} 
于 2011-02-23T12:20:16.453 に答える