在PHP模板系统中渲染循环

时间:2018-01-23 10:01:33

标签: php regex preg-replace

我想从头开始创建一个简单的模板引擎(不使用任何Smarty或twing或任何其他引擎) 到目前为止,我可以渲染任何变量没有问题,但我想渲染一个循环,在我的情况下循环数组$ stuff: 这是我的类Engine.php:

class Engine {
    private $vars = array();

    public function assign($key, $value){
        $this->vars[$key] = $value;
    }

    public function render($template_name){

        if (file_exists($template_name)){
            $content = file_get_contents($template_name);

            foreach ($this ->vars as $key => $value) {
                $content = preg_replace('/\{\{' . $key . '\}\}/', $value, $content);
            }


            eval(' ?> '. $content . '<?php');
        }else{
            exit('<h1>Template error</h1>');
        }
    }

}

这就是我在index.php中所说的:

include_once 'Engine.php';
$template = new Engine;
$template->assign('Name', 'Ismail');
$stuff = array(
    array(
        Thing => "roses",
        Desc => "Red",
    ),
    array(
        Thing => "tree",
        Desc => "green",
    ),
    array(
        Thing => "Sky",
        Desc => "blue",
    ),
);

$template->assign('Stuff', $stuff);
$template->render('template.tmpl');

这是我的template.tmpl:

Hey {{Name}}, 
{{#each Stuff}}
  {{Thing}} are {{Desc}}
{{/each}}

1 个答案:

答案 0 :(得分:0)

您需要编写功能代码。 StackOverflow可以帮助其他人解决问题,而不是为您创建代码。

以一种我实施它的方式推动你:

呼叫:

$template->assign('Stuff', array(
    array(
        Thing => "roses",
        Desc => "Red",
    ),
    array(
        Thing => "tree",
        Desc => "green",
    ),
    array(
        Thing => "Sky",
        Desc => "blue",
    ),
);

发动机:

foreach ($this ->vars as $key => $value) {
    if (is_array($value)) {
        // process your loop here, probably with new foreach,
        // to populate $processedValue by content of your array in $value
        $content = preg_replace('/\{\{#each ' . $key . '.*' . '\/each\}\}/',
            $processedValue, $content);
    } else {
        $content = preg_replace('/\{\{' . $key . '\}\}/', $value, $content);
    }
}