php - Render a base template multi time using Twig
Get the solution ↓↓↓I have a base template contains blocks which has to be filled by some render template's output. The problem is that when I pass$parameters
to$template->render
all twig variable display tags({{ x }})
will be replaced with empty strings. So in next render call there is no block name to be replaced with a new render output.
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());
Output:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
</html>
Expected output:
<!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()
{
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the metadata storage is not up to date, please run the sync-metadata-storage command to fix this issue.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.