django template Syntax

variables html

{{ variable }}django

{{ variable.sttributes}}實際嘗試如下幾種
api

  • Dictionary lookup 字典安全

    

{% for k, v in defaultdict.iteritems %}
    Do something with k and v here...
{% endfor %}

  • Attribute lookup 屬性spa

  • Method call   方法code

  • List-index lookup  列表htm

重點:對象

若是你使用一個不存在變量 ,模板系統使用 TEMPLATE_STRING_IF_INVALID值,若是你在settings定義了,不然就是空‘ ’繼承

Filtersci

ex {{ name| lower}}

鏈式寫法

{{ text|escape|linebreaks }}

參數

{{ bio|truncatewords:30 }}

這種也能夠

{{ list|join:", " }}

django大約提供了30個filters

重點;

{{ value|default:"nothing" }}

傳入變量,但爲none或空  使用默認值,和TEMPLATE_STRING_IF_INVALID有區別

Tags

{% for %} {% endfor%}

{%if%}{%endif%} 

{%if%} {%else%}{%endif%}

{%if%} {%elif%}  {%else%}{%endif%}

exends  繼承


一般使用三級繼承

base.html  base_two.html  base_specific.html 

注意{% block.super%}

指定哪一個block關閉,在有不少個block時很好用

{% block content %}...{% endblock content %}

Automatic HTML escaping  略。自看

說兩點:

爲了安全須要轉義潛在的一些不安全符號

能夠控制轉義仍是不轉義


Accessing method calls

訪問對象的屬性和方法


{% for comment in task.comment_set.all %}
    {{ comment }}
{% endfor %}

注意這個,本身在models裏寫的方法同樣能夠調用
# In model
class Task(models.Model):
    def foo(self):
        return "bar"

# In template{{ task.foo }}

Custom tag and filter libraries  自定義標籤和過濾器


使用{% load xxx %}載入你自定的標籤和過濾器.py名字

能夠有多個{% load %}

Custom libraries and template inheritance


加載自定義標記或濾波器庫時,標籤/過濾器只提供當前的模板使用

例如,若是一個模板foo.html { %load comment % },a child template ,{ %extends「foo.html「% }將沒法使用父模板標籤和過濾器。子模板只對他本身加載的 {% load comments %}負責

相關文章
相關標籤/搜索