遍历模板变量的逻辑


Logic in looping through template variables

我试图开始在我的脚本中使用模板,但是我有问题通过我的模板中的变量循环。我已经创建了一个简单的模板脚本,我的问题是,它只取代了我的变量,而不是所有的。如果我使用.=,问题仍然存在(我当时只替换了一个变量)。谁能帮我的逻辑我的脚本?

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

My HTML template

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

简单的问题,您总是在$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;
}

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

进行以下更改以修复此问题

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