Twig模板继承

来源:互联网 发布:编程老师工资待遇 编辑:程序博客网 时间:2024/05/19 00:35

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">&copy; 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官方文档
可参考include

0 0
原创粉丝点击