开发者

If statements in template system

开发者 https://www.devze.com 2023-02-09 17:12 出处:网络
How can I parse, let\'s say, {if $var > 2} or {if $va开发者_如何学编程r} 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

How can I parse, let's say, {if $var > 2} or {if $va开发者_如何学编程r} 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.


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


use

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

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


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.


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);


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

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


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号