Other auxiliary tags

Some commonly used built-in tags.


Nested references to templatesinclude

Often when making templates, we will extract some public parts, such as header, footer, aside, and other parts, and store them independently. There is no need to write them repeatedly on each page, we just need to introduce them on each page. At this time, we can use include tag.


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

include can embed a split code snippet into the complete document. Used form is{% include "模板文件" %}.

If the template that needs to be introduced does not exist, it will report an error. If we don't know whether the template that needs to be introduced exists, we need to add itif_existsjudge.


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

In this way, if the header.html template exists, it will be introduced. Even if it does not exist, there will be no errors, but it will be ignored.

By default, the template introduced by include will inherit all variables of the current template. If you want to add another variable to the template introduced by include, you can use it.withto increase. like:


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

This defines the title variable for the template introduced by include, and other variables in the current template can also be used.

If you need to declare multiple variables to use for the template introduced by include, you can use it continuouslykey=valueThe form is increased, separated by spaces, such as:


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

If you want only the template introduced by include to use the specified several variables instead of all the variables of the current template, you can use only to limit it:


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

Then use it in header.html:


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


Template code snippet macro functionsmacro

iris.DjangoThe template engine can easily define some macro function code snippets. A macro code snippet is equivalent to a function, which can only call variables passed from parameters. Similar to using include. However, macro has a limited scope. If we use the article item for the article list, we use the article itemmacro:


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

At the same time, macro functions can also be saved to separate files and then nested in through import. When a file contains multiple macro functions, you can use,Multiple macro functions are introduced successively in isolation. You can also use as to set alias:

Save the macro function to archive.helper


{% macro archive_detail(archive) %}
<li class="item">
    <a href="/archive/{{archive.Id}}" class="link">
        <h5 class="title">{{archive.Title}}</h5>
    </a>
</li>
{% endmacro %}
{% macro archive_detail2(archive) %}
<li class="item">
    <a href="/archive/{{archive.Id}}" class="link">
        <h5 class="title">{{archive.Title}}</h5>
    </a>
</li>
{% endmacro %}

Indicated in index.html:


用import引入:
{% import "archive.helper" archive_detail, archive_detail2 as archive_detail_new, archive_detail as new_item %}
调用:
{% for item in archives %}
    {{ archive_detail(item) }}
    {{ archive_detail_new(item) }}
    {{ new_item(item) }}
{% endfor %}


Inheritance of templatesextends

The inheritance of the template is a bit like the master in ppt. We define a skeleton and write a page well, most of which do not need to be changed. The parts that need to be changed are wrapped with block tags:


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

The advantage of this definition is that in the template that inherits it, the block can be rewrite, and if it is not rewrite, it will be displayed according to the master.
For example, we defined a 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/[email protected]/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>

Then inherit this base.html in index.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 %}

This is to use base.html as the master and rewrite the title and content parts in index.html.

Note: If you use the {% extends %}  tag in the template, it must be the first tag in the template. In any other case, template inheritance will not work.

When using inheritance, wrap all the data that may change as much as possible in the block, because even if the block is not rewritten on subsequent pages, it will not affect the parsing of the template, and it is more convenient when it needs to be rewritten.

Similarly, if you write to a certain piece and find that multiple pages need to be used, then add it to base.html and make it a part of the master.


Output of variables

The key to traversing complex data structures in Django templates is period characters., the variable output boundary definition is double braces. There is an object that is people, which has Name, Gender, and Level attributes. The output in the template is:


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


Using struct structure built-in method in template

For example, in the archive list, the built-in functions are defined in the archive structure.func (archive *Archive) GetThumb(), then it can be called directly in the template. like:


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

The template can be used directly{{item.GetThumb()}}To call the built-inarchive.GetThumb()method.


Output current time in template

nowTags provide output of the current time in the template. The parameters of now formatting time follow golang's time formatting rules. If the fake parameter is added, a specific time is output instead of the current time. like:


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


loremRandomly generated Latin sample data

Shows random "lorem ipsum" Latin text. This is useful for providing sample data in templates. That is, placeholding content. When there is no real data for the development template, using this tag can quickly fill in enough random data. like:


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


Template comments

iris.DjangoWe use braces +# to implement comments for comments:{# 注释内容 #}

Single line comments{# 这只能注释单行 #}, use multiple lines of comments{% comment %}这里注释很多行{% endcomment %}.

Example:

Empty single line comments


{# #}

Single line comments


{# testing single line comment #}

Fill in single line comments with valid tags


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

Fill in single line comments with invalid tags


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

Fill in single line comments with invalid syntax


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

Empty block comments


{% comment %}{% endcomment %}

Fill text single line block comments


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

Empty multi-line block comment


{% comment %}


{% endcomment %}

Block comments with other tags


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

Block comments with invalid tags in them


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

Block comments using invalid syntax


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

General labels between comments to ensure that they do not break in the lexer


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