Thẻ mẫu Django
Thẻ mẫu
Trong các mẫu Django, bạn có thể thực hiện logic lập trình như thực thi các câu lệnh if
và vòng lặp for
.
Những từ khóa này, if
và for
, được gọi là "thẻ mẫu" ở Django.
Để thực thi các thẻ mẫu, chúng tôi đặt chúng trong dấu ngoặc {% %}
.
Ví dụ
templates/template.html
:
{% if greeting == 1 %}
<h1>Hello</h1>
{% else %}
<h1>Bye</h1>
{% endif %}
Chạy ví dụ »Mã Django
Các thẻ mẫu là một cách để nói với Django rằng ở đây có thứ gì đó khác ngoài HTML đơn giản.
Thẻ mẫu cho phép chúng tôi thực hiện một số chương trình trên máy chủ trước khi gửi HTML đến máy khách.
templates/template.html
:
<ul>
{% for x in mymembers %}
<li>{{ x.firstname }}</li>
{% endfor %}
</ul>
Chạy ví dụ »Trong các chương tiếp theo, bạn sẽ tìm hiểu về các thẻ mẫu phổ biến nhất.
Tham chiếu thẻ
Danh sách tất cả các thẻ mẫu:
Tag | Description |
---|---|
autoescape | Specifies if autoescape mode is on or off |
block | Specifies a block section |
comment | Specifies a comment section |
csrf_token | Protects forms from Cross Site Request Forgeries |
cycle | Specifies content to use in each cycle of a loop |
debug | Specifies debugging information |
extends | Specifies a parent template |
filter | Filters content before returning it |
firstof | Returns the first not empty variable |
for | Specifies a for loop |
if | Specifies a if statement |
ifchanged | Used in for loops. Outputs a block only if a value has changed since the last iteration |
include | Specifies included content/template |
load | Loads template tags from another library |
lorem | Outputs random text |
now | Outputs the current date/time |
regroup | Sorts an object by a group |
resetcycle | Used in cycles. Resets the cycle |
spaceless | Removes whitespace between HTML tags |
templatetag | Outputs a specified template tag |
url | Returns the absolute URL part of a URL |
verbatim | Specifies contents that should not be rendered by the template engine |
widthratio | Calculates a width value based on the ratio between a given value and a max value |
with | Specifies a variable to use in the block |