【问题标题】:Twig template not including block?树枝模板不包括块?
【发布时间】:2012-08-28 09:36:13
【问题描述】:

我希望开始使用 Twig,但是让 {% block %} 完全工作感到非常头疼 - 我觉得肯定有一些非常明显的东西我遗漏了。

我的 index.php 加载器如下所示:

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);

require_once( "Twig/Autoloader.inc.php" );

Twig_Autoloader::register();

$twig = new Twig_Environment( new Twig_Loader_Filesystem("templates"));

$vars = array (
    "user" => array(
        "name" => "Joe Bloggs"
        ),
    "title" => "My website"
);

$tpl = $twig->loadTemplate("index.html");
echo $tpl->render($vars);

?>

/templatesindex.html 的简化版本如下所示:

<!doctype html>
<html>
<body>
Hello World!
{% block navigation %}Test{% endblock %}
</body>
</html>

/templates 中的 navigation.html 看起来像这样:

{% extends "index.html" %}
{% block navigation %}
<!-- Navigation -->
<nav>
    Some navigation
</nav>
{% endblock %}

据我了解,这应该是块功能的基本工作示例。 Twig 的其他方面对我来说似乎工作得很好,并且没有报告错误。确实,页面成功打印了“Test”。

我应该明确指向某处的 navigation.html 文件,还是 Twig 会自动加载 /templates 文件夹中的所有文件?

【问题讨论】:

  • 我不确定你的问题是什么。你的问题是你得到“测试”而不是你的导航块吗?
  • 是的,确实如此。从所有意图和目的来看,块标签似乎什么也没做。

标签: php templates twig jinja2 template-inheritance


【解决方案1】:

错误:您正在呈现索引模板而不是导航模板。

在索引模板中,导航块包含“测试”,所以你的输出是正确的。如果您渲染 navigation.html,您将从 index.html 中获取 html 内容,并从导航模板中获取导航块(它唯一覆盖的内容)。

您总是需要渲染您希望输出的模板。一个可以扩展许多(例如,您的布局可以扩展所有操作的模板)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-22
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    相关资源
    最近更新 更多