使用Twig多次渲染基本模板

时间:2018-01-09 23:51:54

标签: php symfony twig

我有一个基本模板包含的块必须由一些渲染模板的输出填充。问题是,当我将$parameters传递给$template->render时,所有树枝变量显示标记({{ x }})将被替换为空字符串。因此,在下一个渲染调用中,没有块名称可以替换为新的渲染输出。

basetemplate.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
     {{ Comments }}
</body>
</html>

comments.html:

<comment>
    My new Comment. Count is: {{ count }}
</comment>

View.php

class View
{
    protected static $content = "";

    public static function append($view = "basetemplate.html", $parameters = []){
        self::$content .= self::doRender($view, $parameters);
    }

    public static function getBufferedContent(){
        return self::$content;
    }

     public static function doRender($view, array $parameters = []){
        $twig = Engine::instance();
        $template = $twig->load($view);
        return $template->render($parameters);
    }

    public static function render($blockId, $view, $parameters = []){
        $twig = Engine::instance();
        $template = $twig->createTemplate(self::$content);
        $newTemplate = $template->render([$blockId => 
        self::doRender($view, $parameters)]);            
        self::$content = $newTemplate;
    }
}

Client.php:

View::append("basetemplate.html");
View::render("Comments", "comments.html", ["count" => 10]);
var_dump(View::geyBufferedContent());

输出:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>

预期产出:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <comment>
        My new Comment. Count is: {{ count }}
        <!-- Expected rendered comments.html to be placed here-->
    </comment>
</body>
</html>

And Engine.php:

class Engine
{
    static private $twig;

    public static function instance()
    {
        static $twig = null;
        if(null == $twig){
            $loader = new Twig_Loader_Filesystem(TEMPLATE_ROOT);
            $twig = new Twig_Environment($loader, array(
                'cache' => APP_TEMPLATE_CACHE,
            ));
        }
        return $twig;
    }

    private function __construct()
    {
    }
}

0 个答案:

没有答案