循环模板变量的逻辑

时间:2013-01-07 13:32:18

标签: php templates

我正在尝试在我的脚本中开始使用模板,但是我在模板中循环变量时遇到了问题。 我创建了一个简单的模板脚本,我的问题是它只替换了我的一个变量而不是全部变量。如果我使用.=问题仍然存在(我当时只替换1个变量)。任何人都可以帮我解释我的剧本逻辑吗?

我的PHP

<?php
$data= array('uno'=>'1','dos'=>'2','tres'=>'3','cuatro'=>'4','cinco'=>'5');

function tpl ($data,$tpl = null) {

    foreach ( $data as $find => $replace ) {
            $return = str_replace('{'.$find.'}',$replace,$tpl);
    }

    return $return;
}

echo tpl($data, file_get_contents('tpl.tpl'));
?>

我的HTML模板

<html>
<h1>{uno}</h1>
<h2>{dos}</h2>
<h3>{tres}</h3>
<h4>{cuatro}</h4>
<h5>{cinco}</h5>
</html>

2 个答案:

答案 0 :(得分:2)

简单的问题,您总是在$tpl数据中重新开始替换。始终重写变量内容:

function tpl ($data,$tpl = null) {

    $return  = $tpl; // this will be in foreach and will get rewritten.
    foreach ( $data as $find => $replace ) {
            $return = str_replace('{'.$find.'}', $replace, $return); // note $return from here
    }

    return $return;
}

答案 1 :(得分:0)

您的代码中的问题是,您总是在$ tpl变量的新副本中替换数据,因此这就是您只看到一个变量被替换的原因。每次替换后都必须更新$ tpl变量,以便替换所有变量。

进行以下更改以解决此问题

foreach ( $data as $find => $replace ) {
        $tpl = str_replace('{'.$find.'}',$replace,$tpl);
}

return $tpl;

这将解决您的问题。