04_Django template variable / tag / filter / inheritance url reverse parsing

Posted by glennn.php on Wed, 16 Feb 2022 17:09:06 +0100

Blog 🔗: https://blog.csdn.net/cPen_web
video 🔗: https://www.bilibili.com/video/BV1vK4y1o7jH

Variables and labels

variable

  • Python variables can be encapsulated in the dictionary and passed to the template in the view function

Example:

def xxx_view(request):
    dic = {
        "Variable 1": "Value 1",
        "Variable 2": "Value 2",
    }
    return render(request, 'xxx.html', dic)
  • Data types that can be passed to the template
str-character string	int-integer
list-array	tuple-tuple
dict-Dictionaries	func-method
obj-Class instantiated object
  • Using variable syntax in templates
- {{ Variable name }}
- {{ Variable name.index }}
- {{ Variable name.key }}
- {{ object.method }}
- {{ Function name }}
  • demonstration:
http://127.0.0.1:8000/test_html_param

# mysite1/mysite1/urls.py
urlpatterns = [
    ...
    path('test_html', views.test_html)
]


# mysite1/mysite1/views.py
def test_html_param(request):
    dic = {}
    dic['int'] = 88
    dic['str'] = 'peng'
    dic['lst'] = ['Tom', 'Jack', 'Lily']
    dic['dict'] = {'a':9, 'b':8}
    dic['func'] = say_hi
    dic['class_obj'] = Dog()
    dic['script'] = '<script>alert(1111)</script>'
    return render(request, 'test_html_param.html', dic)

def say_hi():
    return 'hahaha'

class Dog:
    def say(self):
        return 'wangwang'


# mysite1/templates/test_html_param.html
<h3>int yes {{ int|add:"2" }}</h3>
<h3>str yes {{ str|upper }}</h3>
<h3>lst yes {{ lst }}</h3>
<h3>lst yes {{ lst.0 }}</h3>
<h3>dict yes {{ dict }}</h3>
<h3>dict['a'] yes {{ dict.a }}</h3>
<h3>function yes {{ func }}</h3>
<h3>class_obj yes {{ class_obj.say }}</h3>
<h3>script yes {{ script|safe }}</h3>

label

Template label

  • Function: embed some server-side functions into the template, such as process control
  • Label syntax:
{% label %}
...
{% End tag %}

if tag

  • Syntax:
{% if Conditional expression 1 %}
...
{% elif Conditional expression 2 %}
...
{% elif Conditional expression 3 %}
...
{% else %}
...
{% endif %}	- End tag required
  • be careful:
  1. Operators that can be used in if conditional expression = =,! =, <, >, < =, > =, in, not in, is, is not, not,and,or
  2. Using actual parentheses in if tags is invalid syntax. If you want them to indicate priority, you should use nested if tags.

Official documents: https://docs.djangoproject.com/zh-hans/2.2/ref/templates/builtins/#if

  • demonstration:
http://127.0.0.1:8000/test_if_for

# mysite1/mysite1/urls.py
urlpatterns = [
    ...
    path('test_if_for', views.test_if_for),
]

# mysite1/mysite1/views.py
def test_if_for(request):
    dic = {}
    dic['x'] = 20
    dic['lst'] = ['Tom', 'Jack', 'Lily']
    return render(request, 'test_if_for.html', dic)

# mysite1/templates/test_if_for.html
{% if x > 10 %}
the weather is nice today
{% else %}
The weather is very good today.
{% endif %}

<br>

{% for name in lst %}
    {% if forloop.first %} &&&&& {% endif %}
    <p> {{ forloop.counter }}  {{ name }}</p>
    {% if forloop.last %} ===== {% endif %}
{% empty %}
    No data currently
{% endfor %}
  • Template tag - if tag - Exercise

    Write a simple calculator page, which can calculate simple addition, subtraction, multiplication and division at the server (the last filling status of the user and the selection status of the drop-down list need to be recorded)

    • Front end reference code:

    • demonstration:

    http://127.0.0.1:8000/mycal
    

    # mysite1/mysite1/urls.py
    urlpatterns = [
        ...
        path('mycal', views.test_mycal),
    ]
    
    
    # mysite1/mysite1/views.py
    def test_mycal(request):
        if request.method == 'GET':
            return render(request, 'mycal.html')
        elif request.method == 'POST':
            #Processing calculation
            x = int(request.POST['x'])
            y = int(request.POST['y'])
            op = request.POST['op']
    
            result = 0
            if op == 'add':
                result = x + y
            elif op == 'sub':
                result = x - y
            elif op == 'mul':
                result = x * y
            elif op == 'div':
                result = x / y
    
            #dic={'x':x, 'y':y, 'op':op}
            return render(request, 'mycal.html', locals())	# locals method - local variables are directly encapsulated into a dictionary (Python's own method)
    
    
    # mysite1/templates/mycal.html
    <form action='/mycal' method='post'>
        <input type='text' name="x" value="{{ x }}">
        <select name='op'>
        <option value="add"  {% if op == 'add' %}selected{% endif %} > +plus</option>	# ☆ record op status, option selected attribute, using if tag
        <option value="sub"  {% if op == 'sub' %}selected{% endif %}> -reduce</option>
        <option value="mul"  {% if op == 'mul' %}selected{% endif %}> *ride</option>
        <option value="div"  {% if op == 'div' %}selected{% endif %}> /except</option>
        </select>
        <input type='text' name="y" value="{{ y }}"> = <span>{{ result }}</span>
        <div><input type="submit" value='Start calculation'></div>
    </form>
    
    

for tag

  • Syntax:

    {% for variable in Iteratable object %}
        ... Circular statement
    {% empty %}
        ... Statement filled in when the iteratable object has no data
    {% endfor %}
    

    Official documents: https://docs.djangoproject.com/zh-hans/2.2/ref/templates/builtins/#for

  • Built in variable - forloop

  • demonstration:
http://127.0.0.1:8000/test_if_for

# mysite1/mysite1/urls.py
urlpatterns = [
    ...
    path('test_if_for', views.test_if_for),
]

# mysite1/mysite1/views.py
def test_if_for(request):
    dic = {}
    dic['lst'] = ['Tom', 'Jack', 'Lily']
    return render(request, 'test_if_for.html', dic)

# mysite1/templates/test_if_for.html
{% for name in lst %}
    {% if forloop.first %} &&&&& {% endif %}
    <p> {{ forloop.counter }}  {{ name }}</p>
    {% if forloop.last %} ===== {% endif %}
{% empty %}
    No data currently
{% endfor %}

Section

  • Variable call - point method
  • Tag syntax {% tag%} {% end tag%}

Filters and inheritance

filter

  • Definition: process the value of a variable when it is output
  • Function: you can change the output display of variables by using filters
  • Syntax: {{variable | filter 1: 'parameter 1' | filter 2: 'parameter 2'...}}

Official documents: https://docs.djangoproject.com/zh-hans/2.2/ref/templates/builtins/

  • Common filters:

  • demonstration:

http://127.0.0.1:8000/test_html_param

# mysite1/mysite1/urls.py
urlpatterns = [
    ...
    path('test_html', views.test_html)
]


# mysite1/mysite1/views.py
def test_html_param(request):
    dic = {}
    dic['int'] = 88
    dic['script'] = '<script>alert(1111)</script>'
    return render(request, 'test_html_param.html', dic)

def say_hi():
    return 'hahaha'

class Dog:
    def say(self):
        return 'wangwang'


# mysite1/templates/test_html_param.html
<h3>int yes {{ int|add:"2" }}</h3>
<h3>str yes {{ str|upper }}</h3>
<h3>script yes {{ script|safe }}</h3>

inherit

Inheritance of template

The following example:

  • Template inheritance can reuse the contents of the parent template. The child template directly inherits all the contents of the parent template and can overwrite the corresponding blocks in the parent template

  • Syntax - in parent template:

    • Define the * * block * * label in the parent template
    • The table shows which sub modules are allowed to be modified
    • block tag: defined in the parent template and can be overwritten in the child template
  • Syntax - in sub template:

    • Inherit the template extensions tag (written on the first line of the template file)

      For example, {% extensions' base. HTML '%}

    • The child template overrides the content block in the parent template

      {% block block_name %}
      The child template plate is used to cover the parent template block_name Content of block
      {% endblock block_name %}	- block_name Can write but not write
      
  • Overridden override rule

    • If not overridden, it will be displayed according to the effect in the parent template
    • If rewritten, it will be displayed according to the rewriting effect
  • be careful

    • When the template inherits, the dynamic content on the server side cannot be inherited
  • demonstration:

http://127.0.0.1:8000/base_index

# mysite1/mysite1/urls.py
urlpatterns = [
    ...
    path('base_index', views.base_view, name='base_index'),
    path('music_index', views.music_view),
    path('sport_index', views.sport_view),
]

# mysite1/mysite1/views.py
def base_view(request):
    lst = ['Tom', 'Jack']
    return render(request, 'base.html', locals())

def music_view(request):
    return render(request, 'music.html')

def sport_view(request):
    return render(request, 'sport.html')

#-------------------------------------------------------------
# mysite1/templates/base.html		# Parent template
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {% block mytitle %}
    <title>homepage</title>				# Where the sub template can be changed
    {% endblock %}
</head>
<body>
{{ lst }}								# Child templates cannot inherit variables (dynamic content)
<a href="/music_index">Music channel</a>		# Sub template cannot be modified
<a href="/sport_index">Sports channel</a>
<br>


{% block info %}
    This is the home page							# Where the sub template can be changed
{% endblock %}

<br>

<h3>If you have any questions, please contact us xxxx</h3>				# Sub template cannot be modified


# mysite1/templates/music.html		# Sub template
{% extends 'base.html' %}				# Inherit parent template

{% block mytitle %}
    <title>Music channel</title>				# Sub template override block
{% endblock %}

{% block info %}
    Welcome to the music channel
{% endblock %}

# mysite1/templates/sport.html
{% extends 'base.html' %}

{% block mytitle %}
    <title>Sports channel</title>
{% endblock %}

{% block info %}
    Welcome to the sports channel
{% endblock %}

Section

  • filter

    {variable | filter 1: 'parameter value 1' | filter 2: 'parameter value 2'...}

  • Inheritance of template

    Parent template - defines a block that can be modified

    Child template - inherit the parent template; Modify the block defined in the parent template as needed

url reverse parsing

  • Where the url appears in the code

    1. Template [in html]

      1. < a href = 'url' > hyperlink</a>

        Click to jump to url

      2. <form action='url' method='post'>

        The data in the form is submitted to the url using the post method

    2. In the view function - 302 jump to HttpResponseRedirect('url ')

      Jump the address in the user address bar to the url

  • url writing specification in code

    1. Absolute address

      ​ http://127.0.0.1:8000/page/1

    2. Relative address

      1. For the relative address beginning with '= = / = = page/1' - '/', the browser will add this address to the protocol, ip and port in the current address bar as the final access address, that is, if the current page address bar is http://127.0.0.1:8000/page/3 ; The final result of the current relative address is http://127.0.0.1:8000 +/ page/1 (☆ high frequency use)
      2. 'page / 1' - if there is no relative address starting with '/', the browser will add the relative address as the final access address according to the content before the last / of the current url. For example, the current address bar address is== http://127.0.0.1:8000/topic/==detail ; Then the final result of the relative address is http://127.0.0.1:8000/topic/ + page/1
  • demonstration:

http://127.0.0.1:8000/test/url

# mysite1/mysite1/urls.py
urlpatterns = [
    ...
    # http://127.0.0.1:8000/test/url
    path('test/url', views.test_url),
    path('test_url_result', views.test_url_result)
]


# mysite1/mysite1/views.py
def test_url(request):
    return render(request, 'test_url.html')

def test_url_result(request):
    return HttpResponse('---test url res is ok')


# mysite1/templates/test_url.html
<a href="http://127.0.0.1:8000/test_ url_ Result "> absolute address</a>
<a href="/test_url_result">belt'/'Relative address of</a>
<a href="test_url_result">No'/'Relative address of</a>		# The browser resolves to http://127.0.0.1:8000/test/test_url_result

  • url reverse parsing

    • url reverse parsing refers to dynamically finding or calculating the corresponding route with the name defined by path in the view or template

    • Syntax of path function

      • path(route, views, name = "alias")
      • path('page', views.page_view, name="page_url")
      • According to the 'name =' keyword in the path, a unique name is passed to the url. In the template or view, the url information can be inferred from this name in reverse
    • In the template - the reverse resolution of the address is realized through the url tag

      {% url 'alias' %}
      {% url 'alias' 'Parameter value 1' 'Parameter value 2' %}
      ex:
      {% url 'pagen' '400' %}		--- All pass on parameters are str
      {% url 'person' age='18' name='gxn' %}
      
      • Show me: using in templates
      http://127.0.0.1:8000/test/url
      

      # mysite1/mysite1/urls.py
      urlpatterns = [
          ...
          # http://127.0.0.1:8000/test/url
          path('test/url', views.test_url),
          path('test_urls_result/<int:age>', views.test_url_result, name='tr')		# Alias tr
      ]
      
      # mysite1/mysite1/views.py
      def test_url(request):
          return render(request, 'test_url.html')
      
      def test_urls_result(request):
          return HttpResponse('---test url res is ok')
      
      # mysite1/templates/test_url.html
      <a href="{% url 'tr' '100' %}">url Reverse parsing version</a>								# ☆ alias used in template
      
      
    • In the view function → the reverse method in django can be called for reverse parsing

      from django.urls import reverse
      reverse('alias', args=[], kwargs={})
      ex:
      print(reverse('pagen', args=[300]))
      print(reverse('person', kwargs=
      {'name':'peng', 'age':23}))
      
      
      • demonstration:

        http://127.0.0.1:8000/test/url
        
        # 302 jump - the jump address of the location tag in the response header
        

        # mysite1/mysite1/urls.py
        urlpatterns = [
            ...
            path('base_index', views.base_view, name='base_index'),						# Alias base_index
            # http://127.0.0.1:8000/test/url
            path('test/url', views.test_url),
            path('test_urls_result/<int:age>', views.test_url_result, name='tr')		# Alias tr
        ]
        
        
        # mysite1/mysite1/views.py
        def base_view(request):
            lst = ['Tom', 'Jack']
            return render(request, 'base.html', locals())
        
        def test_url(request):
            return render(request, 'test_url.html')
        
        def test_url_result(request, age):
            #302 jump
            from django.urls import reverse
            url = reverse('base_index')													# ☆ alias used in view function
            return HttpResponseRedirect(url)
        
        
        #---------------------------------------------------------------
        # mysite1/templates/test_url.html
        <a href="{% url 'tr' '100' %}">url Reverse parsing version</a>
        
        # mysite1/templates/base.html
         slightly
        
        

Topics: Django