TWIG:使用extends和renderblock渲染多个块

时间:2014-06-24 07:39:48

标签: php twig

我有2个TWIG renderblock正在处理基础和标准模板。这两个块在页面上呈现,{% extends "base.php" %}之前和base.htm中的{% block body %}{% endblock %}之后的所有内容都无法呈现,我明白为什么因为我使用了renderblock而不是render渲染整个模板。 1如何获取整个模板以进行渲染2.除非我使用for循环,否则{% block head %}将不会渲染,我相信有更好的方法可以做到这一点。编辑1:添加了$data2

API

$template = $twig->loadTemplate('event.htm');
echo $template->renderBlock('head', (array('heads' => $data2)));
echo $template->renderBlock('content', (array('events' => $data)));

base.htm

<html>
<head>
{% block head %}
{% for head in heads %}
<title>{{ head.title }}</title>
<meta charset="UTF-8">
</head>
    <body>
<h1>{{ head.title2 }}</h1>
        {% endfor %}
{% endblock %}
{% block body %}{% endblock %}
</body>
</html>

event.htm

{% extends "base.php" %}
{% block content %}
        {% for event in events %}
{{event.uri}}
{{event.desc}}
        {% else %}
no events! 
        {% endfor %}
{% endblock %}

$ DATA2

Array ( [0] => Array ( [id] => 1 [uri] => /event1/1 [title] => some title ) )

2 个答案:

答案 0 :(得分:1)

1 /只要渲染一个块,就会得到该块的内容,仅此而已。

您需要使用以下方式渲染整个模板:

$template = $twig->loadTemplate('event.htm');

echo $template->render(array(
   'heads' => $data2,
   'events' => $data,
));

2 /您需要使用循环,因为$data2包含数组或对象而非预期标题的可能性很大。您应该使用字符串,或者知道您可以访问标头的索引。这很难帮到你,因为我不知道你的$data2变量包含什么,但一个丑陋的解决方案可能就是以这种方式使用reset函数:

echo $template->render(array(
   'heads' => reset($data2),
   'events' => $data,
));

答案 1 :(得分:0)

2 /如果您知道Alain建议的指数(在本例中为0)

echo $template->render(array(
   'heads' => $data2[0],
   'events' => $data,
));