On the Web, tags and syntax tutorials for Django templates are few and far between, and many of them are incomplete, useless articles to copy around, or simply a few tags that, in many cases, are inadequate to use. For example, how to pass variables, how to declare a temporary variable in the page, and so on after include is introduced into the template. In order to solve the problem of lack of introduction content on the Internet, I specially read the iris.Django source code, and sorted out most of the commonly used tags for reference and use.

iris.DjangoTemplate syntax and usage

The template parser for iris.Django template engine is pongo2, which is a template engine similar to Django template syntax. Django is an open source Web application framework written in Python. Its template engine syntax is relatively simple, clear, and easy to use. So we used it as a front-end template engine for our blog.

Nested references to templatesinclude

When we create templates, we will take some common parts (header, footer, aside, etc.) and put them in their own place. We don’t need to repeat them on every page, we just need to introduce them on every page. At this point, we can use the include tag.

{% include "partial/header.html" %}
{% include "partial/footer.html" %}
Copy the code

Include can embed a fragment of code into a complete document. Use {% include “template file” %}.

If the imported template does not exist, an error message is reported. For example, if we do not know whether the imported template exists, we need to add if_exists.

{% include "partial/header.html" if_exists %}
Copy the code

This way, if the header. HTML template exists, it will be introduced, and if it doesn’t, it won’t get an error, just ignored.

By default, the template included by include inherits all variables from the current template. If you want to add additional variables to the template included by include, you can use with to add them. Such as:

{% include"Partial /header. HTML" with title=" This is the title declared for the header "%}
Copy the code

This defines the title variable for the included template, which can also be used for other variables in the current template.

If multiple variables need to be declared for use in the template included with include, they can be consecutively added in the form of key=value, separated by Spaces, for example:

{% include"Partial /header. HTML" with title=" This is the title declared for header "keywords=" This is the keywords declared for header" %}
Copy the code

If you want to include only a few variables in a template, instead of all the variables in the current template, you can use only:

{% include"Partial /header. HTML" with title=" This is the title declared for header. "Keywords =" This is the keywords declared for header." only %}
Copy the code

Then use this in header. HTML:

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

Template snippet macro functionsmacro

The Iris. Django template engine makes it easy to define snippet macros. A macro snippet is equivalent to a function that can only call variables passed in from parameters. Similar to using include. Macro, however, has limited scope. We use macro for the article item of the article list:

Define a macro function{% macro article_detail(article) %}
<li class="item">
    <a href="/article/{{article.Id}}" class="link">
        <h5 class="title">{{article.Title}}</h5>
    </a>
</li>
{% endmacro %}Use defined macro functions{% for item in articles %}
    {{ article_detail(item) }}
{% endfor %}
Copy the code

Macro functions can also be saved to separate files and nested with import. When a file contains multiple macro functions, you can use the partition to introduce multiple macro functions in succession. Aliases can also be set using AS:

Save the macro function to 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 %}
Copy the code

Introduce the following in index.html:

Use import to introduce:{% import "article.helper" article_detail, article_detail2 as article_detail_new, article_detail as new_item %}Call:{% for item in articles %}
    {{ article_detail(item) }}
    {{ article_detail_new(item) }}
    {{ new_item(item) }}
{% endfor %}
Copy the code

Inheritance of templatesextends

Template inheritance is a bit like a PPT master. We define a skeleton, write a page, leave most of it unchanged, and wrap the parts that need to change with the block tag:

{% block title %}
    <title>base</title>  <! Base --> base --> base --> base
{% endblock %}
Copy the code

The advantage of this definition is that the block can be overridden in the template that inherits it and displayed as a master if not overridden. For example, we define a base.html

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {% block title %}
        <title>base</title>  <! Base --> base --> base --> base
    {% endblock %}
    <! Bootstrap core CSS file of the latest version
    <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>
Copy the code

This base. HTML is then inherited 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 %}
Copy the code

This is done by using base. HTML as the master and rewriting 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.

In the case of inheritance, it is possible to wrap data that may change in blocks, because blocks do not affect the parsing of templates even if they are not rewritten on subsequent pages, which is more convenient when overwritten.

Similarly, if more than one page needs to be used when writing a block later, add it to base.html and make it part of the master.

Output of a variable

The key to traversing complex data structures in Django templates is the period character. There is an object called people, which has Name, Gender, and Level attributes. The output in the template is:

<ul>
  <li>Web site:{{siteName}}</li>
  <li>Name:{{people.Name}}</li>
  <li>Gender:{{people.Gender}}</li>
  <li>Rating:{{people.Level}}</li>
</ul>
Copy the code

Filtering of variables

At the same time, when exporting variables, it also supports the use of filters to perform primary filtering on the data. The format is:

{{obj|filter__name:param}}
Copy the code

For example, if a variable has a value, it prints the current value, and if it has no value, it prints the default value:

{{ userName|default:" Warrior Anonymous "}}
Copy the code

Default is considered null if it is empty. We can also do this using default_if_none

{{userName | default_if_none: "warrior anonymous"}}
{{ ""|default_if_none:"n/a" }}
{{ nil|default_if_none:"n/a" }}
Copy the code

Get_digit retrieves the number in the variable. If you specify the value of get_digit, it retrieves the penultimate digit. Such as:

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

Output length with length:

{{ value|length }}
Copy the code

If value is [‘a’, ‘b’, ‘c’, ‘d’], then output is 4.

Divisibleby can determine if a variable is divisible, for example:

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

Date Can format the time:

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

Note that the value must be of type time. time, not a timestamp, which will return an error. The timestamp can either be converted to time. time on the controller, or we can use our custom template function:

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

Truncatechars, truncatewords if the number of characters or words exceeds the specified number of characters, the system truncates them. Truncated strings will be executed in a translatable ellipsis sequence (“…” The end:

{{ value|truncatechars:9}}
{{ value|truncatewords:9}}
Copy the code

Truncation in addition to string truncation truncatechars, truncatewords is also supported

Truncatechars_html and TRUNCateWords_HTML functions are similar to truncatechars and TRUNCateWords. But these two tags are used to manipulate strings in HTML without breaking the HTML structure. One is by character, one is by word. Truncated strings will be executed in a translatable ellipsis sequence (“…” The end:

{{ "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 }}
Copy the code

Upper and lower can convert the case of a single word:

{{ value|upper}}
{{ value|lower}}
Copy the code

Capfirst can capitalize the first letter of a sentence, for example:

{{ "hello there!" |capfirst }}
Copy the code

Cut removes a specific character from a variable. Such as:

{{ 15|cut:"5" }}
{{ "Hello world"|cut: " " }}
Copy the code

Add can append content to output. Equivalent to the + in Golang, numbers are added and output, and strings are concatenated together. Such as:

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

Addslashes adds a backslash before the specified predefined character. These characters are single quotes (‘), double quotes (“), backslashes (\), and NUL (NULL character). Such as:

{{ "plain' text"|addslashes }}
{{ "plain' text"|addslashes|safe }}
Copy the code

The title tag enables you to capitalize the first letter of each word in a sentence and lower the rest of the sentence to format the output of the title. Such as:

{{ "hello there!" |title }}
{{ "HELLO THERE!" |title }}
{{ "HELLO tHERE!" |title }}
Copy the code

Yesno Is used to verify that a variable is valid. Yesno defines three types of results separated by commas, valid, invalid, and unknown types. If it is not defined, it can be left blank. Such as:

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

Striptags StripTags is similar to the STRIp_tags function in PHP. Striptags can strip HTML, XML, and PHP tags from strings. The tag always strips away HTML comments. Such as:

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

The removeTags tag removes the specified HTML tags. Such as:

{{ "Hello! "|removetags:"i"|safe }}
Copy the code

The Pluralize tag determines whether a variable is plural. Such as:

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" }}
Copy the code

Random can output a value in a collection randomly. Such as:

<p>{{ intList|random }}</p>
Copy the code

First and last can be used for the first and last character in an output variable. Such as:

{{ "Test"|first }}
{{ "Test"|last }}
Copy the code

Urlencode The urlenCode tag can encode a variable with a URL percentage sign. Such as:

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

Both the linebreaksbr and linebreaks tags change a linebreak in the value of a variable to

, the equivalent of PHP’s nL2br function. Such as:

{{ article.Description|linebreaksbr }}
{{ article.Description|linebreaks }}
{{ article.Description|linebreaksbr|safe }}
{{ article.Description|linebreaks|safe }}
Copy the code

Length_is Length_IS can determine the length of the value of a variable. You can only judge strings, not numbers. Such as:

{{ "hello"|length_is:5 }}
Copy the code

The INTEGER and float tags convert the value of a variable to an integer or float. Such as:

{{ "foobar"|integer }}
{{" 5.4 "| float | integer}}
{{ "foobar"|float }}
{{" 5.5 "| float}}
{{" 5.6 "| integer | float}}
Copy the code

The floatFormat tag keeps the value of a variable in floating-point format with a specified decimal point. By default, the value is kept as a decimal point. If the last digit is 0, the decimal point is not kept. If the number of decimal points is specified, it is displayed as the specified number of digits. Such as:

{{ 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}}
Copy the code

Join can join an array with a given delimiter and join it together to form a string. Such as:

{{intList|join: ", "}}
Copy the code

A split, as opposed to a join, converts a string to an array with a given delimiter. Such as:

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

Stringformat formats numbers and strings into a specified format for output. Equivalent to fmt.sprintf (). Such as:

{{0.55555 | stringformat: "% 2 f"}}
{{ 888|stringformat:"Test: %d" }}
{{" hello "| stringformat:" Chinese: % s "}}
Copy the code

Make_list splits strings into arrays of characters, equivalent to []rune(” Hello “). Such as:

{{" hello "| make_list |join:", " }}
{% forChar "hello" in | make_list %}{{ char }}.{% endfor %}
Copy the code

The center tag is an interesting way to format a string to a specified length and place the string in the middle, with Spaces beside it. If the given length is less than the string length, no changes are made. Such as:

'{{ "test"|center:3 }}'
'{{ "test"|center:20 }}'
{{ "test"|center:20|length }}
Copy the code

Similar to center, ljust and rjust fill the string to a specified length, but in different directions. Ljust fills in Spaces on the right, leaving the string to the left. Rjust fills space on the left, which makes the string go right. Such as:

'{{ "test"|ljust:"20" }}'
{{ "test"|ljust:"20"|length }}
'{{ "test"|rjust:"20" }}'
{{ "test"|rjust:"20"|length }}
Copy the code

Wordcount counts the length of a string. It can be used in two ways, either after a string or with the filter tag. Such as:

{{ ""|wordcount }}
{% filter wordcount %}{% lorem 25 w %}{% endfilter %}
Copy the code

Wordwrap can wrap a string at a given length. Such as:

{{ "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 }}
Copy the code

Urlize will automatically add a tags to urls, mailboxes, and automatically add rel to nofollow. This is suitable for dealing with the body of the article. Urlize also supports setting true and false to indicate whether the displayed connection content is escaped. Such as:

<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 [email protected] 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>
Copy the code

Urlizetrunc is similar to Urlize, which automatically adds a tag to URL and mailbox. However, it can be set to intercept and display part of URL content. Instead. Such as:

<p>{% filter urlizetrunc:15|safe %}</p>
<p>Please mail me at [email protected] 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>
Copy the code

The escapejs will set the string to the default partial character of the \uxxxx encoding. Such as:

{{ "

aaa

bbbb

"|escapejs|safe }}
Copy the code

Slice can intercept a specified length of data from strings or arrays. Such as:

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

Safe Django templates automatically escape HTML tags and JAVASCRIPT syntactic tags to protect against XSS attacks.

If you don’t want to use escape, use safe to declare that the output is safe and will not escape automatically. You can also use the autoescape tag to turn automatic escape on and off:

Turn off automatic escaping with safe{{ ""|safe}}Forcibly enable automatic escape{% autoescape on %}
{{ "" }}
{% endautoescape %}Forcibly disabling automatic escape is equivalent to enabling safe{% autoescape off %}
{{ "" }}
{% endautoescape %}
Copy the code

Escape Escape can also be used to declare escape. Since escape is already automatic by default, using escape here results in two escapes. Therefore, using autoescape off, followed by escape, equals direct output. Such as:

{{ "" }}The equivalent of{% autoescape off %}
{{ "<script>alert('xss'); </script>"|escape }}
{% endautoescape %}
Copy the code

All of the above filter tags can be used with {% filter tag name %} content {% endfilter %}. Such as:

{% 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>
Copy the code

forIterate over groups, slice, and other objects

For is used to loop through each item in the array, making it available in context variables. For example, to display the list of articles provided in articleList:

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

You can also print the count for the for loop, as well as the remaining number, and use Pluralize to determine if the number is plural. Such as:

{% for item in articles %}
<li class="item">
    <a href="/article/{{item.Id}}" class="link">
        <h5 class="title">The first{{ forloop.Counter }}And the rest of the{{ forloop.Revcounter}}Article,{{forloop. Revcounter | pluralize: "more than 1 article"}}:{{item.Title}}</h5>
    </a>
</li>
{% endfor %}
Copy the code

For can also use reversed arrays, and sorted arrays by int. Such as:

{% 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 %}
Copy the code

For also supports determining whether it is an empty array, nil, etc., using empty to print nonexistent cases. Such as:

{% for item in articles %}
<li class="item">
    <a href="/article/{{item.Id}}" class="link">
        <h5 class="title">{{item.Title}}</h5>
    </a>
</li>
{% empty %}
<div>No content</div>
{% endfor %}
Copy the code

This is equivalent to using the if judgment, but it can be written more succinctly:

{% 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>No content</div>
{% endif %}
Copy the code

Cycle label. In the for loop, we can also use the cycle tag to loop through the variables in the definition one by one.

Each time the cycle tag is encountered, one of its parameters is generated. The first argument is generated on first encounter, the second on second encounter, and so on. Once all parameters are exhausted, the tag loops to the first parameter and produces it again.

This tag is particularly useful in loops. Such as:

{% for item in articles %}
<li class="item">
    <a href="/article/{{item.Id}}" class="link">
        <h5 class="title">Title and Id appear one by one:{% cycle item.Title item.Id %}</h5>
    </a>
</li>
{% endfor %}
Copy the code

Or use as to define an alias and print it through the alias:

{% 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 and Id appear one by one:{{ cycleitem }}</h5>
    </a>
</li>
{% endfor %}
Copy the code

Use mathematical arithmetic calculations in templates

Integers and complex expressions{{10-100}}
{{- (10-100)}}
{{ -(-(10-100)) }}
{{-1 * (-(-(10-100)))}}
* {{- 1 - (-) (10-100) ^ 2) ^ 3 + 3 * (5-17) + 1 + 2}}Float floats{{5.5}}
{{5.172841}}
{{5.5-1.5 == 4}}
{{5.5-1.5 == 4.0}}Multiplication, division, divisible mul/div{{2 * 5}}
{{2 * 5.0}}
{{2 * 0}}
{{2.5 * 5.3}}
1/2} {{}
1/2.0 {{}}
1/0.000001 {{}}The logic expressions are logic expressions{{ !true }}
{{ !(true || false) }}
{{ true || false }}
{{ true or false }}
{{ false or false }}
{{ false || false }}
{{ true && (true && (true && (true && (1 == 1 || false)))) }}Float comparison of floating point numbers{{5.5 <= 5.5}}
{{5.5 < 5.5}}
{{5.5 > 5.5}}
{{5.5 >= 5.5}}So let's take the modulo, let's take the remainders{{ (simple.number+7)%7 }}
{{ (simple.number+7)%7 == 0 }}
{{ (simple.number+7)%6 }}Determine if a variable is in/not in in another result set{{ 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}}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 }}
Copy the code

Removes rows occupied by template logical labels

This requirement is often used, such as in if-elseif or for loops, where it prints empty lines of the if-else tag. If you want to clean up this blank line, you can use – in front or behind the tag to filter, as in:

{% -if false %}
1st choice
{% -elif false %}
2nd choice
{% -elif true %}
3rd choice
{% -endif %}Under the normal{% for item in articles %}
{{ item.Id }}
{% endfor %}Compact:{% for item in articles %}
{{- item.Id }}
{% endfor %}Without a break{% for item in articles -%}
{{ item.Id }}
{% -endfor %}
Copy the code

Use the struct structure body method in the template

For example, in the article list, the article structure defines the built-in function func (article * article) GetThumb(), which can be called directly from the template. Such as:

{% 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 %}
Copy the code

Templates can call the built-in article.GetThumb() method directly with {{item.getThumb ()}}.

Define variables and assign values in the template

The template parser of the Iris.Django template engine provides the with method that you can declare variables in a template and use. With allows us to temporarily declare single or multiple variables for later use. In most cases, we’ll use it with the include tag. Such as:

{% withTitle =" This is the title declared for the header. "Keywords =" This is the keywords declared for the header." %}%} title:{{title}}Key words:{{keywords}}.{% endwith %}
{% include"Partial /header. HTML" with title=" This is the title declared for header "keywords=" This is the keywords declared for header" %}
Copy the code

Variables defined by with need to be wrapped with endWith.

Iris.django also provides a set method for declaring variables that can be used in the current template. Such as:

{% 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
Copy the code

Outputs the current time in the template

The now tag provides output of the current time in the template. The now formatting time parameters follow golang’s formatting rules. If you increment fake, a specific increment time is printed instead of the current time. Such as:

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

loremRandom generation of Latin sample data

Displays random “Lorem ipsum” Latin text. This is useful for providing sample data in templates. That is, placeholder content. Use this tag to quickly populate as much random data as possible when there is no real data in the development template. Such as:

-----
{% lorem %}
-----
{% lorem10%}
-----
{% lorem 3 p %}
-----
{% lorem 100 w %}
-----
Copy the code

Template comments

We use curly braces +# to implement comments: {# comment content #}

Single-line comments use {# this can only comment a single line #}, multi-line comments use {% comment %} where many lines {% endcomment %} are commented.

Example:

Empty one-line comment

{# #}
Copy the code

Single-line comments

{# testing single line comment #}
Copy the code

Populate a single line comment with a valid label

{# testing single line comment {% if thing %}{% endif %} #}
Copy the code

Padding a single line comment with an invalid label

{# testing single line comment {% if thing %} #}
Copy the code

Padding single-line comments with invalid syntax

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

An empty block comments

{% comment %}{% endcomment %}
Copy the code

Fill text single line block comment

{% comment %}filled block comment {% endcomment %}
Copy the code

Empty multiline block comment

{% comment %}


{% endcomment %}
Copy the code

Block comments with other tags

{% comment %}
  {{ thing_goes_here }}
  {% if stuff %}do stuff{% endif %}
{% endcomment %}
Copy the code

Block comments with invalid labels

{% comment %}
  {% if thing %}
{% endcomment %}
Copy the code

Blocking comments with invalid syntax

{% comment %}
  {% thing(") %}
{% endcomment %}
Copy the code

Regular tags between comments to ensure that they are not broken in the lexical analyzer

{% if hello %}
{% endif %}
after if
{% comment %}All done{% endcomment %}
Copy the code

The back end passes variables to the template

In real web development, a variable in a controller needs to be injected into the view using the specific function ctx.viewData (“article”, article) before it can be used in a template. For example, if we define an article in the IndexPage() controller, It is then passed to the template for output.

Let’s start by adding the following code to the IndexPage() function in index.go

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

	article := model.Article{
		Id:          1,
		Title:       "This is an article.",
		Keywords:    "That's the key word.",
		Description: "This is the description.",
		CategoryId:  1,
		Views:       1,
		Category:    model.Category{
			Title: "This is the category name.",
		},
		ArticleData: model.ArticleData{
			ArticleId: 1,
			Content: "
      
contents here
"
, }, } ctx.ViewData("article", article) ctx.View("index.html")}Copy the code

Then print it in the index.html template:

<! DOCTYPEhtml>
<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:{{article.Title}}</div>
<div>Article Classification:{{article.Category.Title}}</div>
<div>The article Id:{{article.Id}}</div>
<div>Release Date:{{stampToDate(article.CreatedTime)}}</div>
<div>Key words:{{article.Keywords}}</div>
<div>Article Description:{{article.Description}}</div>
<div>Article content:{{article.ArticleData.Content|safe}}</div>
</body>
</html>
Copy the code

This way, the template gets the Article variable and prints out all the article members using template syntax.

The complete project sample code is hosted on GitHub. The complete project code can be viewed at github.com/fesiong/gob… You can also fork a copy to make changes on it.