关于django:irisDjango模板引擎的语法格式和语法标签使用方法include标签传递变量方法

13次阅读

共计 17284 个字符,预计需要花费 44 分钟才能阅读完成。

根底配置篇:博客模板的格局语法和后端如何传递数据到模板逻辑

后面的章节中,咱们抉择了应用 iris.Django 作为咱们前端应用的模板引擎,因而咱们这里只介绍它的相干语法。

在网络上,对于 Django 模板的标签和语法教程少之又少,并且很多都是不全面的,要么就是抄来抄去的无用文章,要么就是简略寥寥几个标签,很多时候,都不能满足应用。比方 include 引入模板后,如何传递变量、如何在页面申明一个长期变量等问题。为了解决网络上短少介绍内容的问题,我特意翻读了 iris.Django 的源码,并将大部分罕用到的标签,都整理出来,供参考和应用。

iris.Django模板语法和应用

iris.Django模板引擎的模板解析器是 pongo2,它是一个相似于 Django 模板语法的模板引擎。Django 是一个凋谢源代码 Python 编写的 Web 利用框架。它的模板引擎语法绝对简略,清晰,应用起来也十分不便。因而咱们就应用它做为咱们的博客的前端模板引擎了。

模板的嵌套援用 include

往往制作模板的时候,咱们会将一些公共局部,比方 header、footer、aside 等局部,抽离进去独立寄存,不须要在每一个页面都反复编写,只须要在每一个页面引入它们即可。这个时候,咱们能够应用 include 标签。

{% include "partial/header.html" %}
{% include "partial/footer.html" %}

include 能够将一个拆分进去的代码片段 (fragment) 嵌入到残缺的文档中。应用模式是{% include "模板文件" %}

如果须要引入的模板不存在的话,它会报错,如我咱们不晓得引入的模板是否存在,则须要减少 if_exists 判断。

{% include "partial/header.html" if_exists %}

这样如果 header.html 模板存在的话,则会引入,即便不存在,也不会报错,只是被疏忽掉了。

默认状况下,include 引入的模板,它会继承以后模板的所有变量,如果想给 include 引入的模板减少另外的变量,能够应用 with 来减少。如:

{% include "partial/header.html" with title="这是申明给 header 应用的 title" %}

这样就给 include 引入的模板定义了 title 变量,以后模板的其余变量它同样也能够持续应用了。

如果须要申明多个变量给 include 引入的模板应用,能够间断应用 key=value 的模式减少,它们之间应用空格隔开,如:

{% include "partial/header.html" with title="这是申明给 header 应用的 title" keywords="这是申明给 header 应用的 keywords" %}

如果只想让 include 引入的模板应用指定的几个变量,而不是以后模板的所有变量,能够应用 only 来做限度:

{% include "partial/header.html" with title="这是申明给 header 应用的 title" keywords="这是申明给 header 应用的 keywords" only %}

而后在 header.html 中应用:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{title}}</title>
    <meta name="keywords" content="{{keywords}}">
</head>

模板代码片段宏函数macro

iris.Django模板引擎能够很简便的定义一些宏函数代码片段。宏代码片段相当于一个函数,它只能调用从参数传入的变量。相似于应用 include。不过 macro 有限定的作用域。如文章咱们给文章列表的文章 item 应用macro

定义一个宏函数
{% macro article_detail(article) %}
<li class="item">
    <a href="/article/{{article.Id}}" class="link">
        <h5 class="title">{{article.Title}}</h5>
    </a>
</li>
{% endmacro %}
应用定义的宏函数
{% for item in articles %}
    {{article_detail(item) }}
{% endfor %}

同时宏函数还能够保留到独立的文件中,而后通过 import 来嵌套进来。当一个文件中蕴含多个宏函数,能够应用 , 将隔开间断引入多个宏函数。还能够应用 as 来设置别名:

保留宏函数到 article.helper

{% macro article_detail(article) %}
<li class="item">
    <a href="/article/{{article.Id}}" class="link">
        <h5 class="title">{{article.Title}}</h5>
    </a>
</li>
{% endmacro %}
{% macro article_detail2(article) %}
<li class="item">
    <a href="/article/{{article.Id}}" class="link">
        <h5 class="title">{{article.Title}}</h5>
    </a>
</li>
{% endmacro %}

在 index.html 中引入:

用 import 引入:{% import "article.helper" article_detail, article_detail2 as article_detail_new, article_detail as new_item %}
调用:{% for item in articles %}
    {{article_detail(item) }}
    {{article_detail_new(item) }}
    {{new_item(item) }}
{% endfor %}

模板的继承 extends

模板的继承有点像 ppt 中的母版一样,咱们定义好一个骨架,将一个页面都写好,大部分不必变动,须要变动的局部应用 block 标签包裹起来:

{% block title %}
    <title>base</title>  <!-- 如果扩写了就是扩写的,不扩写就还是用 base -->
{% endblock %}

这样定义的益处是,能够在继承它的模板中,重写这个 block,不重写就按母版来显示。
比方咱们定义了一个 base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {% block title %}
        <title>base</title>  <!-- 如果扩写了就是扩写的,不扩写就还是用 base -->
    {% endblock %}
    <!-- 最新版本的 Bootstrap 外围 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .header {
            width: 100%;
            height: 50px;
            background-color: #369;
        }
    </style>
</head>
<body>

<div class="header"></div>

<div class="container">
    <div class="row">
        <div class="col-md-3">
            {% include 'aside.html' %}
        </div>
        <div class="col-md-9">
            {% block content %}
                <h4>content</h4>
            {% endblock %}
        </div>
    </div>
</div>
</body>
</html>

而后在 index.html 中继承这个 base.html

{% extends 'base.html' %}

{% block title %}
    <title>index</title>
{% endblock %}


{% block content %}
    <div class="col-md-9">
        <h3>index</h3>
        <p>index content</p>
    </div>

{% endblock %}

这样就是应用 base.html 作为母版,并在 index.html 中重写了 title、content 两个局部。

留神:如果你在模版中应用 {% extends %} 标签,它必须是模版中的第一个标签。其余的任何状况下,模版继承都将无奈工作。

在应用继承的状况下,尽可能将可能会变动的数据,都包裹在 block 中,因为 block 即便在后续的页面不重写,也不影响模板的解析,而须要重写的时候就更不便。

同样地,如果后续写到某一块,发现多个页面都须要应用到,那么这时候,就把增加到 base.html 中去,让它成为母版的一部分。

变量的输入

Django 模板中遍历简单数据结构的要害是句点字符.,变量输入边界定义是双大括号。有一个对象是 people,它有 Name、Gender、Level 属性,在模板中输入就是:

<ul>
  <li> 网站:{{siteName}}</li>
  <li> 名字:{{people.Name}}</li>
  <li> 性别:{{people.Gender}}</li>
  <li> 等级:{{people.Level}}</li>
</ul>

变量的过滤

同时,输入变量的时候,还反对应用过滤器,来对数据进行高级过滤,格局是:

{{obj|filter__name:param}}

比方一个变量,当它有值的时候,就输入以后值,没有值的时候,就输入默认值:
应用 default 设置默认值:

{{userName|default:"大侠匿名"}}

default 只有是空都会认为没有。咱们还能够应用 default_if_none 来进行解决

{{userName|default_if_none:"大侠匿名"}}
{{""|default_if_none:"n/a"}}
{{nil|default_if_none:"n/a"}}

get_digit 能够获取变量中的数字,指定 get_digit 的值的话,能够获取倒数第几个数字。如:

{{1234567890|get_digit:0}}
{{1234567890|get_digit}}
{{1234567890|get_digit:2}}
{{1234567890|get_digit:"4"}}
{{1234567890|get_digit:10}}
{{1234567890|get_digit:15}}

应用 length 输入长度:

{{value|length}}

如果 value 是 [‘a’, ‘b’, ‘c’, ‘d’],那么输入是 4。

divisibleby 能够判断一个变量是否能够被整除,如:

{{21|divisibleby:3}}
{{21|divisibleby:"3"}}
{{21|float|divisibleby:"3"}}
{{22|divisibleby:"3"}}
{{85|divisibleby:simple.number}}
{{84|divisibleby:simple.number}}

date 能够格式化工夫:

{{value|date:``"2006-01-02 15:04"}}

留神,这个 value 必须是 time.Time 类型,不是工夫戳,如果是工夫戳它会报错的。工夫戳要么在控制器将它转成 time.Time 类型,要么就应用咱们自定义的模板函数:

{{stampToDate(nowStamp, "2006-01-02 15:04")}}

truncatecharstruncatewords 字符串字符、单词多于指定的字符数量,那么会被截断。截断的字符串将以可翻译的省略号序列(“…”)结尾:

{{value|truncatechars:9}}
{{value|truncatewords:9}}

截断除了字符串截断truncatechars,还反对按单词截断truncatewords

truncatechars_htmltruncatewords_html 性能相似truncatecharstruncatewords。然而这这 2 个标签用来解决截取 html 中的字符串,它不会毁坏 html 构造。一个是按字符截取,一个是按单词截取。截断的字符串将以可翻译的省略号序列(“…”)结尾:

{{"This is a long test which will be cutted after some chars."|truncatechars_html:25}}
{{"This is a long test which will be cutted after some words."|truncatewords_html:5|safe}}

upperlower 能够对单字进行大小写转换:

{{value|upper}}
{{value|lower}}

capfirst 能够实现句子首字母大写成果,如:

{{"hello there!"|capfirst}}

cut 可实现删除变量中特定的字符。如:

{{15|cut:"5"}}
{{"Hello world"|cut: " "}}

add 能够对要输入的内容进行追加。相当于 golang 中的+,数字则会相加后输入后果,字符串则会拼接在一起。如:

{{5|add:6}}
{{5|add:nothing}}
{{5|add:"test"}}
{{"hello"|add:"john doe"}}

addslashes 则会在指定的预约义字符前增加反斜杠。这些字符是单引号(’)、双引号(”)、反斜线(\)与 NUL(NULL 字符)。如:

{{"plain' text"|addslashes}}
{{"plain' text"|addslashes|safe}}

title 标签能够实现句子中每一个单词的首字母都变成大写,并将其余部分变成小写,用于格式化题目的输入。如:

{{"hello there!"|title}}
{{"HELLO THERE!"|title}}
{{"HELLO tHERE!"|title}}

yesno yesno 用于验证一个变量是否无效,它能够定义三种后果,三种后果别离用英文逗号 , 隔开,有效值、有效值、不晓得类型。如果不定义,也能够留空。如:

{{article.Status|yesno}}
{{article.Status|yesno:"validated,not validated,unknown validation status"}}

striptags striptags 相似 PHP 的 strip_tags 函数,能够剥去字符串中的 HTML、XML 以及 PHP 的标签。该标签始终会剥离 HTML 正文。如:

{{"<title>Hello World</title>"|striptags}}
{{"<title>Hello World</title>"|striptags|safe}}

removetags 标签能够删除指定的 html 标签。如:

{{"<strong><i>Hello!</i></strong>"|removetags:"i"|safe}}

pluralize 标签能够判断一个变量是否是复数。如:

customer{{0|pluralize}}
customer{{1|pluralize}}
customer{{2|pluralize}}
cherr{{0|pluralize:"y,ies"}}
cherr{{1|pluralize:"y,ies"}}
cherr{{2|pluralize:"y,ies"}}
walrus{{0|pluralize:"es"}}
walrus{{1|pluralize:"es"}}
walrus{{simple.number|pluralize:"es"}}

random 能够随机输入汇合中的一个值。如:

<p>{{intList|random}}</p>

firstlast 能够用于输入变量中的最开始一个字符和最初一个字符。如:

{{"Test"|first}}
{{"Test"|last}}

urlencode urlencode 标签能够对变量进行 url 百分号编码。如:

{{"https://www.kandaoni.com/?category_id=1"|urlencode}}

linebreaksbrlinebreaks 两个标签都能够将变量的值中的换行符变成 <br/>,相当于 PHP 的nl2br 函数。如:

{{article.Description|linebreaksbr}}
{{article.Description|linebreaks}}
{{article.Description|linebreaksbr|safe}}
{{article.Description|linebreaks|safe}}

length_is length_is 能够判断变量的值的长度。只能判断字符串,数字是不行的。如:

{{"hello"|length_is:5}}

integerfloat 标签能够将变量的值转换成整数、浮点数。如:

{{"foobar"|integer}}
{{"5.4"|float|integer}}
{{"foobar"|float}}
{{"5.5"|float}}
{{"5.6"|integer|float}}

floatformat 标签能够将变量的值按浮点数格局保留指定小数点,默认只保留认为,如果末位是 0,则不保留小数点。如果指定小数点后位数,则按指定位数显示。如:

{{34.23234|floatformat}}
{{34.00000|floatformat}}
{{34.23234|floatformat:3}}
{{34.00000|floatformat:3}}
{{"34.23234"|floatformat}}
{{"34.00000"|floatformat}}
{{"34.23234"|floatformat:3}}
{{"34.00000"|floatformat:3}}

join 能够将一个数组按给定的分隔符合并在一起成为字符串。如:

{{intList|join:","}}

split 刚好和 join 相同,它能够将一个字符串按给定的分隔符将一个字符串转换成数组。如:

{{"Hello, 99, 3.140000, good"|split:","|join:","}}

stringformat 能够将数字、字符串格式化成指定的格局输入。相当于fmt.Sprintf()。如:

{{0.55555|stringformat:"%.2f"}}
{{888|stringformat:"Test: %d"}}
{{"你好"|stringformat:"Chinese: %s"}}

make_list 能够将字符串按字符拆分成数组,相当于[]rune("你好啊")。如:

{{"你好啊"|make_list|join:","}}
{% for char in "你好啊"|make_list %}{{char}},{% endfor %}

center 这个标签比拟有意思,能够将字符串格式化成指定长度,并将字符串放在两头,旁边应用空格填充。如果给定的长度小于字符串长度,则不会做扭转。如:

'{{"test"|center:3}}'
'{{"test"|center:20}}'
{{"test"|center:20|length}}

ljustrjust 这两个标签和 center 差不多,都是给字符串填充到指定长度,然而填充方向不同。ljust会在左边填充空格,即让字符串靠左。rjust会在右边填充空格,即让字符串靠右。如:

'{{"test"|ljust:"20"}}'
{{"test"|ljust:"20"|length}}
'{{"test"|rjust:"20"}}'
{{"test"|rjust:"20"|length}}

wordcount 用来统计字符串的长度。它有 2 种应用形式,一种是在字符串前面,另一种是应用 filter 标签。如:

{{""|wordcount}}
{% filter wordcount %}{% lorem 25 w %}{% endfilter %}

wordwrap 能够将字符串按给定的长度换行。如:

{{"hello world"|wordwrap:2}}
<pre>{% filter wordwrap:5 %}{% lorem 26 w %}{% endfilter %}</pre>
{{"Lorem ipsum dolor sit amet, consectetur adipisici elit."|wordwrap:2|linebreaksbr|safe}}

urlize 会主动给 url、邮箱增加上 a 标签,并主动减少 nofollow 的 rel。这个用来解决文章正文比拟适合。urlize 还反对设置 true 和 false,用来阐明显示的连贯内容是否本义。如:

<p>{{"https://www.kandaoni.com"|urlize|safe}}</p>
<p>{{"www.kandaoni.com"|urlize|safe}}</p>
<p>{{"kandaoni.com"|urlize|safe}}</p>
<p>{% filter urlize:true|safe %}</p>
<p>Please mail me at demo@example.com or visit mit on:</p>
<p>- lorem ipsum http://www.kandaoni.com lorem ipsum</p>
<p>- lorem ipsum https://www.kandaoni.com lorem ipsum</p>
<p>- lorem ipsum https://www.kandaoni.com lorem ipsum</p>
<p>- lorem ipsum www.kandaoni.com lorem ipsum</p>
<p>- lorem ipsum www.kandaoni.com/test="test" lorem ipsum</p>
<p>{% endfilter %}</p>
<p>{% filter urlize:false|safe %}</p>
<p>- lorem ipsum www.kandaoni.com/test="test" lorem ipsum</p>
<p>{% endfilter %}</p>

urlizetrunc 的作用和 urlize 差不多,都是主动给 url、邮箱增加上 a 标签,然而能够设置截取显示局部 url 内容,超过指定长度局部应用 ... 代替。如:

<p>{% filter urlizetrunc:15|safe %}</p>
<p>Please mail me at demo@example.com or visit mit on:</p>
<p>- lorem ipsum http://www.kandaoni.com lorem ipsum</p>
<p>- lorem ipsum https://www.kandaoni.com lorem ipsum</p>
<p>- lorem ipsum https://www.kandaoni.com lorem ipsum</p>
<p>- lorem ipsum www.kandaoni.com lorem ipsum</p>
<p>- lorem ipsum www.kandaoni.com/test="test" lorem ipsum</p>
<p>{% endfilter %}</p>

escapejs 会将字符串按 \uxxxx 编码预设的局部字符。如:

{{"<p>aaa</p><script>alert('xss');</script><p>bbbb</p>"|escapejs|safe }}

slice 能够对字符串、数组进行截取指定长度的数据。如:

{{"Test"|slice:"1:"}}
{{"Test"|slice:":3"}}
{{"Test"|slice:"1:3"|join:","}}
{{intList|slice:"1:5"|join:","}}

safe Django 的模板中会对 HTML 标签和 JS 等语法标签进行主动本义,这样是为了平安,避免 xss 攻打。

如果不想用本义,就应用 safe 来申明要输入的内容是平安的,它就不会主动本义,也能够应用 autoescape 标签来管制开启和敞开主动本义:

用 safe 敞开主动本义
{{"<script>alert('xss');</script>"|safe}}
强制开启主动本义
{% autoescape on %}
{{"<script>alert('xss');</script>" }}
{% endautoescape %}
强制敞开主动本义,相当于应用了 safe
{% autoescape off %}
{{"<script>alert('xss');</script>" }}
{% endautoescape %}

escape escape 还能够进行申明本义。因为默认曾经会主动本义,因而在此应用 escape 的话,会造成本义 2 次。因而应用 autoescape off 敞开本义后,再应用 escape 就等于间接输入。如:

{{"<script>alert('xss');</script>" }}
相当于
{% autoescape off %}
{{"<script>alert('xss');</script>"|escape }}
{% endautoescape %}

下面所有的 filter 标签,都能够应用 {% filter 标签名 %} 内容{% endfilter %} 来应用。比方:

{% filter lower %}This is a nice test; let's see whether it works. Foobar. {{simple.xss}}{% endfilter %}

{% filter truncatechars:10|lower|length %}This is a nice test; let's see whether it works. Foobar. {{simple.number}}{% endfilter %}

<p>{% filter urlize:false|safe %}</p>
<p>- lorem ipsum www.kandaoni.com/test="test" lorem ipsum</p>
<p>{% endfilter %}</p>

for 遍历数组、slice 等对象

for用于循环拜访数组中的每个我的项目,从而使该我的项目在上下文变量中可用。例如,要显示 articleList 中提供的文章列表:

{% for item in articles %}
<li class="item">
    <a href="/article/{{item.Id}}" class="link">
        <h5 class="title">{{item.Title}}</h5>
    </a>
</li>
{% endfor %}

还能够输入 for 循环的计数,以及残余数量,还能够应用 pluralize 判断数量是否是复数。如:

{% for item in articles %}
<li class="item">
    <a href="/article/{{item.Id}}" class="link">
        <h5 class="title"> 第 {{forloop.Counter}} 篇,残余 {{forloop.Revcounter}} 篇,{{forloop.Revcounter|pluralize:"多于 1 篇"}}:{{item.Title}}</h5>
    </a>
</li>
{% endfor %}

for 还能够应用 reversed 翻转数组,sorted按 int 排序数组。如:

{% for item in articles reversed %}
<li class="item">
    <a href="/article/{{item.Id}}" class="link">
        <h5 class="title">{{item.Title}}</h5>
    </a>
</li>
{% endfor %}
{% for item in articles sorted %}
<li class="item">
    <a href="/article/{{item.Id}}" class="link">
        <h5 class="title">{{item.Title}}</h5>
    </a>
</li>
{% endfor %}
{% for item in articles reversed sorted %}
<li class="item">
    <a href="/article/{{item.Id}}" class="link">
        <h5 class="title">{{item.Title}}</h5>
    </a>
</li>
{% endfor %}

for还反对判断是否为空数组或者 nil 等,应用 empty 来输入不存在的状况。如:

{% for item in articles %}
<li class="item">
    <a href="/article/{{item.Id}}" class="link">
        <h5 class="title">{{item.Title}}</h5>
    </a>
</li>
{% empty %}
<div> 没有内容 </div>
{% endfor %}

它等价于应用 if 判断,然而这样写能够更简洁:

{% if articles %}
{% for item in articles %}
<li class="item">
    <a href="/article/{{item.Id}}" class="link">
        <h5 class="title">{{item.Title}}</h5>
    </a>
</li>
{% endfor %}
{% else %}
<div> 没有内容 </div>
{% endif %}

cycle 标签。在 for 循环中,咱们还能够应用 cycle 标签,来循环一一输入定义中的变量。

每次遇到此 cycle 标签时,都会产生其参数之一。第一个参数在第一次遇到时产生,第二个参数在第二次遇到时产生,依此类推。一旦所有参数用尽,标记将循环到第一个参数并再次产生它。

此标记在循环中特地有用。如:

{% for item in articles %}
<li class="item">
    <a href="/article/{{item.Id}}" class="link">
        <h5 class="title">Title,Id 一一呈现:{% cycle item.Title item.Id %}</h5>
    </a>
</li>
{% endfor %}

或者应用as 来定义别名,再通过别名输入:

{% for item in articles %}
<li class="item">
    <a href="/article/{{item.Id}}" class="link">
        {% cycle item.Title item.Id as cycleitem %}
        <h5 class="title">Title,Id 一一呈现:{{cycleitem}}</h5>
    </a>
</li>
{% endfor %}

在模板中应用数学算术计算

整数和复数表达式 integers and complex expressions
{{10-100}}
{{-(10-100) }}
{{-(-(10-100)) }}
{{-1 * (-(-(10-100))) }}
{{-1 * (-(-(10-100)) ^ 2) ^ 3 + 3 * (5 - 17) + 1 + 2 }}

浮点数 floats
{{5.5}}
{{5.172841}}
{{5.5 - 1.5 == 4}}
{{5.5 - 1.5 == 4.0}}

乘法、除法、整除 mul/div
{{2 * 5}}
{{2 * 5.0}}
{{2 * 0}}
{{2.5 * 5.3}}
{{1/2}}
{{1/2.0}}
{{1/0.000001}}

逻辑表达式 logic expressions
{{!true}}
{{!(true || false) }}
{{true || false}}
{{true or false}}
{{false or false}}
{{false || false}}
{{true && (true && (true && (true && (1 == 1 || false)))) }}

浮点数比拟 float comparison
{{5.5 <= 5.5}}
{{5.5 < 5.5}}
{{5.5 > 5.5}}
{{5.5 >= 5.5}}

取模、取余 remainders
{{(simple.number+7)%7 }}
{{(simple.number+7)%7 == 0 }}
{{(simple.number+7)%6 }}

判断一个变量是否在另一个后果集中 in/not in
{{5 in simple.intmap}}
{{2 in simple.intmap}}
{{7 in simple.intmap}}
{{!(5 in simple.intmap) }}
{{not(7 in simple.intmap) }}
{{1 in simple.multiple_item_list}}
{{4 in simple.multiple_item_list}}
{{!(4 in simple.multiple_item_list) }}
{{"Hello" in simple.misc_list}}
{{"Hello2" in simple.misc_list}}
{{99 in simple.misc_list}}
{{False in simple.misc_list}}

associativity for infix operators
{{34/3*3}}
{{10 + 24 / 6 / 2}}
{{6 - 4 - 2}}

int const 与 uint 比拟 uint comparison with int const
{{simple.uint}}
{{simple.uint == 8}}
{{simple.uint == 9}}
{{simple.uint >= 8}}
{{simple.uint <= 8}}
{{simple.uint < 8}}
{{simple.uint > 8}}

移除模板逻辑标签占用的行

这个需要很多时候会用到,比方在 if-elseif 中 或者是 for 循环中,它会连 if-else 标签局部的行的空行也输入。如果想清理这一行空行,能够在标签外面的后方或前方应用 - 来实现过滤, 如:

{%- if false %}
1st choice
{%- elif false %}
2nd choice
{%- elif true %}
3rd choice
{%- endif %}
失常下
{% for item in articles %}
{{item.Id}}
{% endfor %}
紧凑:{% for item in articles %}
{{- item.Id}}
{% endfor %}
不带换行
{% for item in articles -%}
{{item.Id}}
{%- endfor %}

在模板中应用 struct 构造体内置办法

比方在 article 列表中,article 的构造体中,定义了内置函数func (article *Article) GetThumb(),那么在模板中,是能够间接调用的。如:

{% for item in articles %}
<li class="item">
    <a href="/article/{{item.Id}}" class="link">
        <img src="{{item.GetThumb()}}" alt="{{item.Title}}" />
        <h5 class="title">{{item.Title}}</h5>
    </a>
</li>
{% endfor %}

模板能够间接应用 {{item.GetThumb()}} 来调用内置的 article.GetThumb() 办法。

在模板中定义变量并赋值

iris.Django模板引擎的模板解析器提供了能够在模板中申明变量并应用的办法 with。通过with 咱们能够长期申明单个或多个变量,提供后续应用。少数状况下,咱们会将它配合 include 标签应用。如:

{% with title="这是申明给 header 应用的 title" keywords="这是申明给 header 应用的 keywords" %} %}题目:{{title}},关键词:{{keywords}}。{% endwith %}
{% include "partial/header.html" with title="这是申明给 header 应用的 title" keywords="这是申明给 header 应用的 keywords" %}

with定义的变量须要应用 endwith 来包裹。

另外 iris.Django 还提供 set 的形式来申明变量,这个变量能够在以后模板应用。如:

{% set new_var = "hello" %}{{new_var}}
{% block content %}{% set new_var = "world" %}{{new_var}}{% endblock %}
{{new_var}}{% for item in simple.misc_list %}
{% set new_var = item %}{{new_var}}{% endfor %}
{{new_var}}
{% set car=someUndefinedVar %}{{car.Drive}}No Panic

在模板中输入以后工夫

now标签提供在模板中输入以后工夫。now 格式化工夫的参数遵循 golang 的工夫格式化规定。如果减少 fake 参数,则会输入一个特定的加工夫代替以后工夫。如:

{% now "Mon Jan 2 15:04:05 -0700 MST 2006" fake %}
{% now "2006-01-02 15:04" %}

lorem 随机生成拉丁文样本数据

显示随机的“lorem ipsum”拉丁文本。这对于在模板中提供样本数据很有用。也就是占位内容。在开发模板没有实在数据的时候,应用这个标签能够疾速填充足够多的随机数据。如:

-----
{% lorem %}
-----
{% lorem 10 %}
-----
{% lorem 3 p %}
-----
{% lorem 100 w %}
-----

模板的正文

iris.Django的正文咱们应用大括号 +# 来实现正文:{# 正文内容 #}

单行正文应用 {# 这只能正文单行 #},多行正文应用 {% comment %}这里正文很多行{% endcomment %}

示例:

空单行正文

{# #}

单行正文

{# testing single line comment #}

用无效标签填充单行正文

{# testing single line comment {% if thing %}{% endif %} #}

用有效标签填充单行正文

{# testing single line comment {% if thing %} #}

用有效语法填充单行正文

{# testing single line comment {% if thing('') %}wow{% endif %} #}

空块正文

{% comment %}{% endcomment %}

填充文本单行块正文

{% comment %}filled block comment {% endcomment %}

空多行块正文

{% comment %}


{% endcomment %}

阻止带有其余标签的正文

{% comment %}
  {{thing_goes_here}}
  {% if stuff %}do stuff{% endif %}
{% endcomment %}

阻止其中带有有效标签的正文

{% comment %}
  {% if thing %}
{% endcomment %}

应用有效语法阻止正文

{% comment %}
  {% thing('') %}
{% endcomment %}

正文之间的惯例标签,以确保其在词法分析器中不会中断

{% if hello %}
{% endif %}
after if
{% comment %}All done{% endcomment %}

后端传递变量到模板

理论网站开发中,咱们在控制器中的变量,须要应用特定的函数 ctx.ViewData("article", article) 注入到 view 中,能力在模板中应用这个变量,比方,咱们在 IndexPage()控制器中定义一个 article,而后将它传递到模板中,用来输入。

咱们先在 index.go 中的 IndexPage() 函数中增加如下代码

func IndexPage(ctx iris.Context) {nowStamp := time.Now().Unix()
    ctx.ViewData("nowStamp", nowStamp)

    article := model.Article{
        Id:          1,
        Title:       "这是一篇文章",
        Keywords:    "这是关键词",
        Description: "这是形容",
        CategoryId:  1,
        Views:       1,
        Category:    model.Category{Title: "这是分类名称",},
        ArticleData: model.ArticleData{
            ArticleId: 1,
            Content: "<div> 内容在此 </div>",
        },
    }
    ctx.ViewData("article", article)
    ctx.View("index.html")
}

而后在 index.html 模板中输入:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello World</title>
</head>
<body>
Hello World!<br>
{{stampToDate(nowStamp, "2006-01-02 15:04:05")}}<br>
<div> 文章题目:{{article.Title}}</div>
<div> 文章分类:{{article.Category.Title}}</div>
<div> 文章 Id:{{article.Id}}</div>
<div> 公布工夫:{{stampToDate(article.CreatedTime)}}</div>
<div> 文章关键词:{{article.Keywords}}</div>
<div> 文章形容:{{article.Description}}</div>
<div> 文章内容:{{article.ArticleData.Content|safe}}</div>
</body>
</html>

这样,就模板就取得了 article 变量,而后通过模板语法,将 article 的成员都输入了。

残缺的我的项目示例代码托管在 GitHub 上,须要查看残缺的我的项目代码能够到 github.com/fesiong/goblog 上查看,也能够间接 fork 一份来在下面做批改。

正文完
 0