Python – Django: Cú pháp trong HTML

Biến trong Django:

{# templates/main.html #}
<h1>Hello {{ firstname }}</h1>

{# create variables #}
{% with firstname="Tobial" %}
<p>Hello {{ firstname }}</p>
{% endwith %}

Template tag:

{% if greeting == 1 %}
    <h1>Hello</h1>
{% elif greeting == 2 %}
{% else %}
    <h1>Bye</h1>
{% endif %}

{# if with and/or #}
{% if (greeting == 1 and day == "Monday") or greeting == 2 %}
{% for x in members %}
    <li>{{ x.firstname }}</li>
{% endfor %}

Reversed:

For x in members reversed để truy vấn từ dưới lên.

Empty:

{% for x in memers %}
  <li>{{ x.firstname }}</li>
{% empty %}
  <li>No member</li>
{% endfor %}

Các biến trong loop:

  • forloop.counter: đếm vòng lặp, bắt đầu từ 1.
  • forloop.counter0: đếm từ 0.
  • forloop.first: check loop đầu tiên.
  • forloop.last: check loop cuối cùng.
  • forloop.revcounter0: đếm ngược.

Comment: sẽ không hiển thị khi render.

{% comment %}
  <h1>Comment</h1>
{% endcomment %}

Comment với mô tả: {% comment "This is description" %}.

Comment trong 1 dòng: {# comment in a line #}.

Include tag:

<h1>Hello</h1>
{% include 'footer.html' %}

Bạn có thể gửi biến vào template bằng with:

{% include "menu.html" with item1="Home" item2="About" %}

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *