Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

An introduction to the common syntax and variables of Django

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "introduction of common syntax and variables of Django". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Common grammar

Only two special symbols need to be memorized: {{}} and {%}

Variables are related to {{}} and logically related to {%}.

Variable

Use this syntax in Django's template language: {{variable name}}.

Note:

-if the value of the calculated result is callable, it will be called without parameters. The result of the call becomes the value of the template. -if the variable used does not exist, the template system inserts the value of the string_if_invalid option, which is set to''(empty string) by default.

Code in view:

Def template_test (request): l = [11,22,33] d = {"name": "alex"} class Person (object): def _ _ init__ (self, name, age): self.name = name self.age = age def dream (self): return "{} is dream..." .format (self.name) Alex = Person (name= "Alex") Age=34) Egon = Person (name= "Egon", age=9000) Eva_J = Person (name= "Eva_J", age=18) person_list = [Alex, Egon, Eva_J] return render (request, "template_test.html", {"l": l, "d": d, "person_list": person_list})

Supported writing methods in templates:

{# take the first parameter in l, #} {{l.0}} {# take the value of key in the dictionary #} {{d.name} {# take the object's name attribute #} {{person_list.0.name}} {#. The operation can only call the method #} {{person_list.0.dream}} Filters without parameters (filter, variable dependent)

In Django's template language, the display of variables is changed by using filters.

Syntax of filter: {{value | filter_name: parameter}}

Note:

-the filter supports "chain" operation. That is, the output of one filter is used as the input of another filter. -the filter can accept parameters, such as {{sss | truncatewords:30}}, which displays the first 30 words of sss. -if the filter parameter contains spaces, it must be wrapped in quotation marks. For example, use commas and spaces to connect elements in a list, such as: {{list | join:','} -'| 'there are no spaces commonly used in the built-in filtersdefault

If a variable is false or empty, the given default value is used. Otherwise, the value of the variable is used.

{{value | default: "nothing"}} display nothinglength if value has no value or the value is empty

Returns the length of the value, acting on strings and lists.

{{value | length}} returns the length of value, such as value= ['axed,' baked, 'clocked,' d'], then 4filesizeformat is displayed.

Format the value to a "human readable" file size (for example, 13 KB, 4.1 MB, 102 bytes, etc.)

{{value | filesizeformat}} if value is 123456789, the output will be 117.7 MBslice

Slice

{{value | slice: "2date"} date

Format output time

{{value | date: "Y-m-d H:i:s"}} safe

Syntax tags such as HTML tags and JS are automatically escaped in Django templates.

Value = "click me" {{value | safe}} truncatechars

If the string character is more than the specified number of characters, it will be truncated. The truncated string ends with a translatable sequence of ellipsis (".").

{{value | truncatechars:9}} parameter: number of characters truncated cut

Remove all strings in value that are the same as the given variable

{{value | cut:''}} if value is' iloveyou', then 'iloveyou'.join will be output

Concatenate the list using strings, such as Python's str.join (list)

Timesince

Take an optional parameter, which is a variable containing the date used as the comparison point (without parameters, the comparison point is now).

{{blog_date | timesince:comment_date}} for example, if blog_date is a date instance that represents midnight on June 1, 2006, and comment_date is a date instance at 08:00 on June 1, 2006, the following will return "8 hours"

Minutes is the smallest unit used, and 0 minutes is returned for any future date relative to the comparison point.

Custom filter custom filter code file storage location app01/ _ _ init__.py models.py templatetags/ # create a new package package _ _ init__.py app01_filters.py # under app01 build a file to store custom filter views.py write custom filterfrom django import templateregister = template.Library () @ register.filter (name= "cut") def cut (value, arg): return value.replace (arg "") @ register.filter (name= "addSB") def add_sb (value): return "{} SB" .format (value) in the page using custom filter {# first import our custom filter file #} {% load app01_filters%} {# use our custom filter #} {{somevariable | cut: "0"} {{d.name | addSB} Tags (logically related) for cycle normal for cycle {% For user in user_list%} {{user.name}} {% endfor%}

Some parameters available for the for loop:

Index value of VariableDescriptionforloop.counter current cycle (starting at 1) Index value of forloop.counter0 current cycle (starting at 0) reverse index value of forloop.revcounter current loop (starting from 1) reverse index value of forloop.revcounter0 current cycle (starting from 0) forloop.first current cycle is not the first cycle (Boolean) forloop.last current cycle is not the last cycle (Boolean) forloop.parentloop the outer loop of this loop. Empty {% for user in user_list%} {{user.name}} {% empty%} empty {% endfor%} if judges {% if user_list%} number of users: {{user_list | length}} {% elif black_list%} number of blacklists: {{black_list | length} {% else%} there are no users {% endif%}

Of course, it's just if and else.

{% if user_list | length > 5%} Seven-seater luxury SUV {% else%} rickshaw {% endif%}

If statements support and, or, = =, >, b > c%}... {% endif%}

In Django's template language, attributes take precedence over methods.

Def xx (request): d = {"a": 1, "b": 2, "c": 3, "items": "100"} return render (request, "xx.html", {"data": d})

As above, when we use the render method to render a page, the dictionary d passed has a key of items and a default d.items () method, which is in the template language:

{{data.items}}

The value of items key of d is taken by default.

Title {% block page-css%} {% endblock%} this is the title of the motherboard {% block page-main%} {% endblock%} the bottom content of the motherboard {% block page-js%} {% endblock%} inherits the motherboard

In the child page, use the following syntax at the top of the page to inherit the motherboard.

{% extends' layouts.html'%} blocks (block)

Define "blocks" by using {% block xxx%} in the motherboard. In the child page, define the block name in the motherboard to correspond to the corresponding content in the replacement motherboard.

{% block page-main%}

The situation of the world is weak.

Human feelings are evil

Flowers are easy to fall when rain sends dusk.

{% endblock%} component

You can save commonly used page content such as navigation bar, footer information and other components in a separate file, and then import it according to the following syntax where you need to use it.

{% include 'navbar.html'%}

Note: the component page only needs to write the content in the tag.

Static file {% static%} {% load static%}

Hi!

{% load static%}

A file is used in multiple places to save as a variable

{% load static%} {% static "images/hi.jpg" as myphoto%}

{get_static_prefix} {load static}

Hi!

Or

{load static} {get_static_prefix as STATIC_PREFIX}

Hi!

Hello!

Custom Tagssimple_tag

Similar to custom filter, except that it receives more flexible parameters

Define registration simple tag

@ register.simple_tag (name= "plus") def plus (a, b, c): return "{} + {}" .format (a, b, c)

Use a custom simple tag

{% load app01_demo%} {# simple tag #} {% plus "1"2"abc"%}

To customize the file directory structure and storage rules of Tags, please refer to Custom filter

Inclusion_tag

Mostly used to return html code snippets

Custom templatetags/my_inclusion.py

From django import templateregister = template.Library () @ register.inclusion_tag ('result.html') def show_results (n): n = 1 if n < 1 else int (n) data = ["item {}" .format (I) for i in range (1,1)] return {"data": data}

Html snippet code templates/snippets/result.html

{% for choice in data%} {{choice}} {% endfor%}

Use templates/index.html

Inclusion_tag test {% load inclusion_tag_test%} {% show_results 10%}

This is the end of the introduction to the common syntax and variables of Django. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report