twig引用模板

来源:互联网 发布:淘宝网天猫超市批发 编辑:程序博客网 时间:2024/06/05 03:20

controller内容:

    public function index() {        return $this->render();    }

view\index.html内容:

引用三个页面

{% include 'head.html' %}  {% include 'content.html' %}  {% include 'footer.html' %}  

head.html内容:

<!DOCTYPE html>  <html>      <head>              <title>This Title</title>       </head> 

content.html内容:

<body>      <div id="content">This Content</div>  </body>

footer.html内容:

    <script type="text/javascript">        alert('This Footer');    </script></html>

解析后的内容:

<html>    <head>          <title>This Title</title>       </head>     <body>          <div id="content">This Content</div>          <script type="text/javascript">            alert('This Footer');        </script>    </body></html>

变量使用:

  • controller内传递到模板中使用:

    public function index() {        return $this->render(                array(                    'time'=>date("Y-m-d H:i:s"),                    )            );    }
<div id="time">当前时间是:{{time}}</div> 

四个页面每个页面都可以使用。

  • 引用赋值

可在footer.html中使用param_time

{% include 'footer.html' with {'param_time': time} %}  
  • 模板内set赋值参数:

{% set title = '这是标题'%}<title>{{title}}</title>
  • 禁用变量

{% set time_param = time %}{% include 'head.html' only%}  {% include 'content.html' only %}  {% include 'footer.html' %}  <!--body中使用没有任何效果--><body>      <div id="content">This Content</div>      <div id="time">当前时间是:{{time_param}}</div>      <div id="time">当前时间是:{{time}}</div>  </body>
  • 引用的模板不存在

下面的代码可以忽略报错

{% include 'sidebar.html' ignore missing %}
  • 数组方式传入要引用的模板

检测模板是否存在,存在则引用,不存在则忽略。

{% include ['content.html', 'footer.html'] %}

参考官方文档

0 0
原创粉丝点击