django+sqlite進行web開發(二)

模板

前面的例子中,咱們是直接將HTML寫在了Python代碼中,這種寫法並不可取。咱們須要使用模板技術將頁面設計和Python代碼分離。html

模板一般用於產生HTML,可是Django的模板也能產生任何基於文本格式的文檔。django

參考http://djangobook.py3k.cn/2.0/chapter04/,對如下例子模板:app

<html>
<head><title>Ordering notice</title></head>

<body>

<h1>Ordering notice</h1>

<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>

<p>Here are the items you've ordered:</p>

<ul>
{% for item in item_list %}
    <li>{{ item }}</li>
{% endfor %}
</ul>

{% 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>

</body>
</html>
  • 用兩個大括號括起來的文字(例如 {{ person_name }} )被成爲變量。意味着在此處插入指定變量的值。
  • 被大括號和百分號包圍的文本(例如 {% if ordered_warranty %} )是模板標籤,通知模板系統完成耨寫工做的標籤。這個例子中有包含if和for兩種標籤。
  • if標籤就是相似Python中的if語句;而for標籤就是相似Python中的for語句。
  • 這個例子中還使用了filter過濾器((例如 {{ ship_date|date:"F j, Y" }}),它是一種最便捷的轉換變量輸出格式的方式。

使用模板系統

在Python代碼中使用Django模板的最基本方式以下:url

  • 能夠用原始的模板代碼字符串建立一個 Template 對象;
  • 調用模板對象的render方法,而且傳入一套變量context。模板中的變量和標籤會被context值替換。

例子以下:spa

>>> from django import template
>>> t = template.Template('My name is {{ name }}.')
>>> c = template.Context({'name': 'Adrian'})
>>> print t.render(c)
My name is Adrian.
>>> c = template.Context({'name': 'Fred'})
>>> print t.render(c)
My name is Fred.

建立模板文件:

咱們先給咱們的testapp添加一個add視圖,即在views.py中添加:.net

def add(request):
    return render(request, 'add.html')

在testapp目錄下新件一個templates文件夾,裏面新建一個add.html。默認狀況下,Django會默認找到app目錄下的templates文件夾中的模板文件。設計

而後在add.html中寫一些內容:code

<!DOCTYPE html>
<html>
<head>
    <title>歡迎光臨</title>
</head>
<body>
Just Test
</body>
</html>

更新url配置,即在urls.py中添加:orm

from testapp.views import add

urlpatterns = [
 ......
    url(r'^add/$', add),
]

重啓服務後即可以訪問http://127.0.0.1:8000/add/htm

接下來嘗試在html文件中放入動態內容。

顯示一個基本的字符串在網頁上。

views.py:

def add(request):
    string = "這是傳遞的字符串"
    return render(request, 'add.html', {'string': string})

即向add.html傳遞一個字符串名稱爲string。在字符串中這樣使用: add.html

{{ string }}

使用for循環顯示list

修改views.py:

def add(request):
    testList = ["Python", "C++", "JAVA", "Shell"]
    return render(request, 'add.html', {'testList': testList})

修改add.html:

{% for i in testList %}
    {{i}}
    {% endfor %}

顯示字典中內容

修改views.py:

def add(request):
    testDict = {"1":"Python", "2":"C++", "3":"JAVA", "4":"Shell"}
    return render(request, 'add.html', {'testDict': testDict})

修改add.html:

{% for key,value in testDict.items %}
        {{key}} : {{value}}
    {% endfor %}

更多有用的操做能夠參考https://code.ziqiangxuetang.com/django/django-template2.html

相關文章
相關標籤/搜索