国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python Django模板的使用方法(圖文)

2020-02-23 04:56:55
字體:
來源:轉載
供稿:網友

模版基本介紹
模板是一個文本,用于分離文檔的表現形式和內容。 模板定義了占位符以及各種用于規范文檔該如何顯示的各部分基本邏輯(模板標簽)。 模板通常用于產生HTML,但是Django的模板也能產生任何基于文本格式的文檔。
來一個項目說明
1、建立MyDjangoSite項目具體不多說,參考前面。
2、在MyDjangoSite(包含四個文件的)文件夾目錄下新建templates文件夾存放模版。
3、在剛建立的模版下建模版文件user_info.html
代碼如下:
<html>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>用戶信息</title>
    <head></head>
    <body>
        <h3>用戶信息:</h3>
        <p>姓名:{{name}}</p>
        <p>年齡:{{age}}</p>
    </body>
</html>

說明:{{ name }}叫做模版變量;{% if xx %} ,{% for x in list %}模版標簽。

4、修改settings.py 中的TEMPLATE_DIRS
導入import os.path
添加 os.path.join(os.path.dirname(__file__), 'templates').replace('//','/'),
代碼如下:
TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.

    #"E:/workspace/pythonworkspace/MyDjangoSite/MyDjangoSite/templates",
    os.path.join(os.path.dirname(__file__), 'templates').replace('//','/'),
)

說明:指定模版加載路徑。其中os.path.dirname(__file__)為當前settings.py的文件路徑,再連接上templates路徑。

5、新建視圖文件view.py
代碼如下:
#vim: set fileencoding=utf-8:

#from django.template.loader import get_template
#from django.template import Context
#from django.http import HttpResponse
from django.shortcuts import render_to_response

def user_info(request):
    name = 'zbw'
    age = 24
    #t = get_template('user_info.html')
    #html = t.render(Context(locals()))
    #return HttpResponse(html)
    return render_to_response('user_info.html',locals())

說明:Django模板系統的基本規則: 寫模板,創建 Template 對象,創建 Context , 調用 render() 方法。
可以看到上面代碼中注釋部分
#t = get_template('user_info.html') #html = t.render(Context(locals()))
#return HttpResponse(html)
get_template('user_info.html'),使用了函數 django.template.loader.get_template() ,而不是手動從文件系統加載模板。 該 get_template() 函數以模板名稱為參數,在文件系統中找出模塊的位置,打開文件并返回一個編譯好的 Template 對象。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 大足县| 黄平县| 千阳县| 泗阳县| 长沙县| 广汉市| 龙江县| 舟山市| 海原县| 专栏| 桑植县| 时尚| 灵山县| 彝良县| 青海省| 乃东县| 西乌| 昌宁县| 孝感市| 阿拉善右旗| 东宁县| 大安市| 宁武县| 河曲县| 杭锦后旗| 东阿县| 白玉县| 芮城县| 合肥市| 桐梓县| 永仁县| 墨竹工卡县| 吉隆县| 湄潭县| 海原县| 旺苍县| 肥乡县| 克拉玛依市| 宜川县| 柞水县| 锦州市|