controller内容:
public function base() {
return $this->render();
}
view内容
base.html
{% extends "index.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ parent() }}
<style type="text/css">
.important { color: #336699; }
</style>
{% endblock %}
{% block content %}
<h1>Index</h1>
<p class="important">
Welcome on my awesome homepage.
</p>
{% endblock %}
继承index.html内容:
<!DOCTYPE html>
<html>
<head>
{% block head %}
<link rel="stylesheet" href="style.css" />
<title>{% block title %}{% endblock %} - My Webpage</title>
{% endblock %}
</head>
<body>
<div id="content">{% block content %}{% endblock %}</div>
<div id="footer">
{% block footer %}
© Copyright 2011 by <a href="http://domain.invalid/">you</a>.
{% endblock %}
</div>
</body>
</html>
twig解析后的内容:
<html>
<head>
<link rel="stylesheet" href="style.css" />
<title>Index - My Webpage</title>
<style type="text/css">.important { color: #336699; }</style></head>
<body>
<div id="content">
<h1>Index</h1>
<p class="important">Welcome on my awesome homepage.</p></div>
<div id="footer">© Copyright 2011 by
<a href="http://domain.invalid/">you</a>.</div>
</body>
</html>
继承的原理:
base页继承index页,然后按照block合并(或替换)内容并继承index页面。
base页先继承index页,然后把block title合并到index的block title。
base页在把block head 合并到index的block head,不同的是base把index页的head内容继承过来了(parent)。
<head>
<!--link来自index页面-->
<link rel="stylesheet" href="style.css" />
<!--Index是base页面的,My Webpage是index页面的。-->
<title>Index - My Webpage</title>
<!--style来自base页面-->
<style type="text/css">.important { color: #336699; }</style>
</head>
后面的内容和上面的方式一样。
注:block name是唯一性的。
extends在页面的开始位置。
好像不能多层继承,没测试,有兴趣的可以试试。
本文介绍了一个使用Twig模板引擎实现的简单页面继承示例。通过base.html继承index.html,并利用block标签进行内容覆盖与扩展,展示了如何在一个网页项目中有效地复用布局与组件。
1663

被折叠的 条评论
为什么被折叠?



