Summary of today's learning content 5.2

Summary of today's learning content

Template syntax

Template syntax filter

Filter description

    1. be similar to Python Built in method for

    2. Pass the data on the left side of the vertical bar as the first parameter to the filter on the right

    3. grammar : {{ [data]|filter:Optional parameters }}

    4. be careful : There is no space on the left and right sides of the vertical bar

    5. If the filter parameter contains spaces, it needs to be wrapped in quotation marks

    6. The filter can have at most two parameters

Grammatical structure

    {{ data object|Filter name:parameter }}  The filter can only transmit one additional parameter at most

Use of common filters

django template syntax provides 60 + filters. We can understand the common filters.

    <p>Length of Statistics:{{ s1|length }}</p>
    <p>Arithmetic addition or string addition:{{ n1|add:111 }},{{ s1|add:'big baby' }}</p>
    <p>Convert numbers to appropriate document units of measure:{{ file_size|filesizeformat }},{{ file_size1|filesizeformat }}</p>
    <p>Judge whether the Boolean value corresponding to the current data object is False:{{ b|default:'The Boolean value corresponding to the previous value is False' }},{{ s1|default:'The Boolean value corresponding to the previous value is False' }}</p>
    <p>Time formatting:{{ ctime|date:'Y-m-d' }}</p>
    <p>Index slice:{{ s1|slice:'0:8' }}</p>
    <p>Intercept the specified number of text according to the space:{{ s2|truncatewords:5 }},{{ s1|truncatewords:1 }}</p>
    <p>Intercept text according to the number of characters(Contains three points):{{ s2|truncatechars:5 }},{{ s1|truncatechars:10 }}</p>
    <p>Removes the specified character:{{ info|cut:'|' }}</p>
    <p>Cancel conversion:{{ tag1 }},{{ tag1|safe }},{{ scripts1|safe }},{{ res }}</p>

The last | safe inspired us to develop the front-end page code (mainly HTML code) of the full stack project with django in the future. It can also be written on the back-end:

    from django.utils.safestring import mark_safe
    html_safe = mark_safe('<h1>Hello</h1>')

Label of template syntax

When writing labels in django template syntax, you can only write keywords, and then the tab key will be completed automatically.

Grammatical structure

  {% name ...%}

  {% end name %}

if judgment

  {% if Condition 1 %}
    <p>How do you do</p>
  {% elif Condition 2 %}
    <p>How is he</p>
  {% else %}
    <p>hello everyone</p>
  {% endif %}

for loop

The forloop keyword is provided

    {% for i in l %}
        <p>{{ forloop }}</p>
        <p>{{ i }}</p>  # Loop takes elements from the list l
    {% endfor %}

    # forloop outputs
    {'parentloop': {}, 'counter0': 0, 'counter': 1, 'revcounter': 4, 'revcounter0': 3, 'first': True, 'last': False}

    counter0    Indexes
    counter     First element
    revcounter  First element in reverse order
    revcounter0 invert index 
    first       Is it the first element
    last        Is it the last element

Mixed use of for and if

    {% for i in l %}
        {% if forloop.first %}
            <p>is first</p>
        {% elif forloop.last %}
            <p>is last</p>
        {% else %}
            <p>{{ i }}</p>
        {% endif %}
    {% endfor %}

with: alias

    {% with ll.2.hobby.0 as hb %}
        <p>{{ hb }}</p>             # Alias values can be used
        <p>{{ ll.2.hobby.0 }}</p>   # You can also use the original method
    {% endwith %}

Dictionary values, keys, items methods

    {% for k in d.keys %}
        <p>{{ k }}</p>
    {% endfor %}

    {% for v in d.values %}
        <p>{{ v }}</p>
    {% endfor %}

    {% for kv in d.items %}
        <p>{{ kv }}</p>
    {% endfor %}

Custom filters, labels, inclusion_tag

Create templatetags file

    1. First, create a name under the application, which must be called"templatetags"folder
    2. Create a folder with any name under the change folder py file (example : mytag)
    3. In this py Two lines of code are fixed in the document
          from django import template
          register = template.Library()

Custom filter

A custom filter can have at most two formal parameters.

    from .templatetags.mytag import register

    # The name specified here is used when importing custom filters in the template layer
    def sums(a, b):   # Name any function
        return a + b  # Returns the sum of two parameters
    {% load mytag %}  # Import tag file
    <p>{{ i|myfilter:100 }}</p>  # Use myfilter filter

Custom label

Custom tags can receive any parameters.

    from .templatetags.mytag import register

    # The name specified here is used when importing custom labels in the template layer
    def my_join(a,b,c,d):          # Arbitrary function name
        return f'{a}/{b}/{c}/{d}'  # Returns the result of parameter splicing

    {% load mytag %}  # Import tag file
    <p>{% my_tag 'hello' 'pai' 'da' 'xing' %}</p>  # Multiple parameters after the tag are separated from each other by spaces

    # Custom inclusion_tag
    from .templatetags.mytag import register

    @register.inclusion_tag('test.html',name='my_incl_tag')  # The first parameter is the HTML page that needs to be rendered
    def func(n):
        for i in range(n):
            data.append(f'The first{i}page')
        return locals()

    # test.html file
    {% load mytag %}
    <p>{% my_incl_tag 6 %}</p>

    # test2.html
    {{ data }}
    {% for foo in data %}
        {% if forloop.first %}
        {% elif forloop.last %}
            <p>{{ foo }}</p>
        {% else %}
            <p>{{ foo }}</p>
        {% endif %}
    {% endfor %}

This method needs to act on a local html page first, and then put the rendered result at the call location. Internal principle:

    1. stay HTML Import the written in the page inclusion_tag And called

    2. Triggered py The execution of a function in the file and produce results
    3. The resulting result is passed to a through the template syntax HTML Render the page

    4. After rendering, it returns the call inclusion_tag Location of

      test. Inclusion called in HTML page_ Tag ----- > trigger the execution of a function to produce the result and render it to test2 In the HTML page, after rendering, return to test HTML page.


Import of template

It is similar to making partial pages on html pages into modules, where you want to import directly.

    {% include 'edit.html' %}  # Display edit directly in the current HTML file Content of HTML file

    <!---->  yes HTML Annotation syntax for
    {##} 		  Is a comment on the django template syntax
    HTML Comments can be viewed directly on the front-end browser page
    The comments of template syntax can only be viewed in the back-end, but not in the front-end browser

Inheritance of template

Use of template inheritance

To inherit a template, you first need to select a template page in which you can use block to delimit the area that can be changed:

    # Motherboard page 'home HTML 'file
    {% block [Area name] %}
    {% endblock %}

The page you want to inherit can use extensions to inherit a page.

    # Sub version
    {% extends 'home.html' %}
    {% block [Area name] %}
    {% endblock %}

The sub version inherits the template, so the overall format of the sub version is the same as that of the template. The areas divided by the block can be changed at will.

Child pages can also reuse the content of the parent page.

    {{ block.super }}

Three areas of the template

There should be at least three areas on the template:

    {% block css %}
        # css area
    {% endblock %}

    {% block content %}
        # HTML region
    {% endblock %}

    {% block js %}
        # js area
    {% endblock %}

The purpose is to make the sub version have independent css, js, etc., and increase scalability.

Posted by pluginbaby on Mon, 16 May 2022 17:40:13 +0300