Twig模板继承

本文介绍了一个使用Twig模板引擎实现的简单页面继承示例。通过base.html继承index.html,并利用block标签进行内容覆盖与扩展,展示了如何在一个网页项目中有效地复用布局与组件。

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值