Django模板語言

變量

爲了便於演示,以下是views.py的代碼

def test(request):
    num = [1,2,3,4]
    dir = {'lemon':'luouo','banana':'haha','apple':'bubu'}
    hub = [(1,2),(3,4),(5,6)]

    class Commodity(object):
        def __init__(self,name,price):
            self.name=name
            self.price = price

        def feel(self):
            return '%s is too expensive' %self.name

    house = Commodity('house','One hundred million')
    car = Commodity('car','One hundred thousand')
    dream=[house,car]

    return render(request,'test.html',{'Num':num,'Dir':dir,'Dream':dream,'Hub':hub})

html中的用法

{{ Num }} #顯示[1,2,3,4]
{{ Num.0 }} #取第一個值
{{ Dir.lemon }} #取字典中lemon的值
{{ Dream.0.name }} #取對象name的屬性
{{ Dream.0.feel }} #取對象的feel方法的返回值 house is too expensive

標籤

  • if標籤
{% if Num.0 == 1 %}
<h1>等於一</h1>
{% endif %}

其中可以增加類似{% elif Num.1 == 2 %}或{% else %}的邏輯判斷

  • for標籤
#正向迭代
{% for foo in Num %}
<h1>{{ foo }}</h1>
{% endfor %}
#反向迭代
{% for foo in Num reversed %}
<h1>{{ foo }}</h1>
{% endfor %}
#二元組輸出
{% for a,b in Hub %}
<h1>{{ a }}{{ b }}</h1>
{% endfor %}
#對字典解包
{% for a,b in Dir.items %}
<h1>{{ a }}----------{{ b }}</h1>
{% endfor %}
{% empty %} #在for循環中,定義列表位空輸出的內容
{{ forloop.counter }} #for循環中的計數器,從1開始
{{ forloop.counter0 }} #for循環中的計數器,從0開始
{{ forloop.revcounter }} #for循環中的倒數計數器,從元素總個數開始直到1
{{ forloop.revcounter0 }}  #for循環中的倒數計數器,從元素總個數-1開始直到0
{{ forloop.first }} #一個布爾值,當第一次for循環的時候爲True
{{ forloop.last }} #一個布爾值,最後一個for循環的時候爲True
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章