Django學習筆記

Django模板系統的基本規則: 寫模板,建立 Template  對象,建立 Context  , 調用 render()  方法。
>>> from django.template import Template, Context
>>> raw_template = """<p>Dear {{ person_name }},</p>
...
... <p>Thanks for placing an order from {{ company }}. It's scheduled to
... ship on {{ ship_date|date:"F j, Y" }}.</p>
...
... {% if ordered_warranty %}
... <p>Your warranty information will be included in the packaging.</p>
... {% else %}
... <p>You didn't order a warranty, so you're on your own when
... the products inevitably stop working.</p>
... {% endif %}
...
... <p>Sincerely,<br />{{ company }}</p>"""
>>> t = Template(raw_template)
>>> import datetime
>>> c = Context({'person_name': 'John Smith',
...     'company': 'Outdoor Equipment',
...     'ship_date': datetime.date(2009, 4, 2),
...     'ordered_warranty': False})
>>> t.render(c)
u"<p>Dear John Smith,</p>\n\n<p>Thanks for placing an order from Outdoor
Equipment. It's scheduled to\nship on April 2, 2009.</p>\n\n\n<p>You
didn't order a warranty, so you're on your own when\nthe products
inevitably stop working.</p>\n\n\n<p>Sincerely,<br />Outdoor Equipment
</p>"

Python 的「真值」 html

在Python和Django模板系統中,如下這些對象至關於布爾值的False 程序員

  • 空列表([] ) django

  • 空元組(() ) 函數

  • 空字典({} ) ui

  • 空字符串('' ) spa

  • 零值(0 ) code

  • 特殊對象None orm

  • 對象False(很明顯) htm

from django.template.loader import get_template   #使用加載模板函數

t = get_template('your template's name', dictionary)
模板函數的路徑在settings.py 中 TEMPLATE_DIRS 定義
對象

render_to_response()
from django.shortcuts import render_to_response
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    return render_to_response('current_datetime.html', {'current_date': now})

locals() 技巧

若是你是個喜歡偷懶的程序員並想讓代碼看起來更加簡明,能夠利用 Python 的內建函數 locals() 。它返回的字典對全部局部變量的名稱與值進行映射。 所以,前面的視圖能夠重寫成下面這個樣子:

def current_datetime(request):
    current_date = datetime.datetime.now()
    return render_to_response('current_datetime.html', locals())
 locals() 的值,它囊括了函數執行到該時間點時所定義的一切變量。 所以,咱們將 now 變量重命名爲 current_date ,由於那纔是模板所預期的變量名稱。 

 {% block %} 
 全部的 {% block %} 標籤告訴模板引擎,子模板能夠重載這些部分。 每一個{% block %}標籤所要作的是告訴模板引擎,該模板下的這一塊內容將有可能被子模板覆蓋。

相關文章
相關標籤/搜索