搜尋
首頁後端開發Python教學python Django模板的使用方法

模版基本介绍
模板是一个文本,用于分离文档的表现形式和内容。 模板定义了占位符以及各种用于规范文档该如何显示的各部分基本逻辑(模板标签)。 模板通常用于产生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 id="用户信息">用户信息:</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&#39;t forget to use absolute paths, not relative paths.
    #"E:/workspace/pythonworkspace/MyDjangoSite/MyDjangoSite/templates",
    os.path.join(os.path.dirname(__file__), &#39;templates&#39;).replace(&#39;\\&#39;,&#39;/&#39;),
)

说明:指定模版加载路径。其中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 = &#39;zbw&#39;
    age = 24
    #t = get_template(&#39;user_info.html&#39;)
    #html = t.render(Context(locals()))
    #return HttpResponse(html)
    return render_to_response(&#39;user_info.html&#39;,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 对象。
render(Context(locals()))方法接收传入一套变量context。它将返回一个基于模板的展现字符串,模板中的变量和标签会被context值替换。其中Context(locals())等价于Context({'name':'zbw','age':24}) ,locals()它返回的字典对所有局部变量的名称与值进行映射。
render_to_response Django为此提供了一个捷径,让你一次性地载入某个模板文件,渲染它,然后将此作为 HttpResponse返回。


6、修改urls.py

 from django.conf.urls import patterns, include, url
from MyDjangoSite.views import user_info
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns(&#39;&#39;,
    # Examples:
    # url(r&#39;^$&#39;, &#39;MyDjangoSite.views.home&#39;, name=&#39;home&#39;),
    # url(r&#39;^MyDjangoSite/&#39;, include(&#39;MyDjangoSite.foo.urls&#39;)),
    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r&#39;^admin/doc/&#39;, include(&#39;django.contrib.admindocs.urls&#39;)),
    # Uncomment the next line to enable the admin:
    # url(r&#39;^admin/&#39;, include(admin.site.urls)),
    url(r&#39;^u/$&#39;,user_info),

)

7、启动开发服务器
基本一个简单的模版应用就完成,启动服务看效果!
效果如图:

python Django模板的使用方法

模版的继承
减少重复编写相同代码,以及降低维护成本。直接看应用。
1、新建/templates/base.html

<html>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>{% block title %}{% endblock %}</title>
    <head></head>
    <body>
        <h3 id="nbsp-block-nbsp-headTitle-nbsp-nbsp-endblock-nbsp">{% block headTitle %}{% endblock %}</h3>
        {% block content %} {% endblock %}
        {% block footer %}
            <h3 id="嘿-这是继承了模版">嘿,这是继承了模版</h3>
        {% endblock%}
    </body>
</html>

2、修改/template/user_info.html,以及新建product_info.html
urser_info.html

{% extends "base.html" %}
{% block title %}用户信息{% endblock %}

<h3 id="nbsp-block-nbsp-headTitle-nbsp-用户信息-nbsp-endblock-nbsp">{% block headTitle %}用户信息:{% endblock %}</h3>
{% block content %}
<p>姓名:{{name}}</p>
<p>年龄:{{age}}</p>
{% endblock %}

product_info.html

{% extends "base.html" %}
{% block title %}产品信息{% endblock %}
<h3 id="nbsp-block-nbsp-headTitle-nbsp-产品信息-nbsp-endblock-nbsp">{% block headTitle %}产品信息:{% endblock %}</h3>
{% block content %}
    {{productName}}
{% endblock %}

3、编写视图逻辑,修改views.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 = &#39;zbw&#39;
    age = 24
    #t = get_template(&#39;user_info.html&#39;)
    #html = t.render(Context(locals()))
    #return HttpResponse(html)
    return render_to_response(&#39;user_info.html&#39;,locals())
def product_info(request):
    productName = '阿莫西林胶囊'
    return render_to_response('product_info.html',{'productName':productName})

4、修改urls.py

from django.conf.urls import patterns, include, url
from MyDjangoSite.views import user_info,product_info
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns(&#39;&#39;,
    # Examples:
    # url(r&#39;^$&#39;, &#39;MyDjangoSite.views.home&#39;, name=&#39;home&#39;),
    # url(r&#39;^MyDjangoSite/&#39;, include(&#39;MyDjangoSite.foo.urls&#39;)),
    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r&#39;^admin/doc/&#39;, include(&#39;django.contrib.admindocs.urls&#39;)),
    # Uncomment the next line to enable the admin:
    # url(r&#39;^admin/&#39;, include(admin.site.urls)),
    url(r&#39;^u/$&#39;,user_info),
    url(r&#39;^p/$&#39;,product_info),
)

5、启动服务效果如下:

python Django模板的使用方法

更多XXXXXX相关文章请关注PHP中文网!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
什麼是Python Switch語句?什麼是Python Switch語句?Apr 30, 2025 pm 02:08 PM

本文討論了版本3.10中介紹的Python的新“匹配”語句,該語句與其他語言相同。它增強了代碼的可讀性,並為傳統的if-elif-el提供了性能優勢

Python中有什麼例外組?Python中有什麼例外組?Apr 30, 2025 pm 02:07 PM

Python 3.11中的異常組允許同時處理多個異常,從而改善了並發方案和復雜操作中的錯誤管理。

Python中的功能註釋是什麼?Python中的功能註釋是什麼?Apr 30, 2025 pm 02:06 PM

Python中的功能註釋將元數據添加到函數中,以進行類型檢查,文檔和IDE支持。它們增強了代碼的可讀性,維護,並且在API開發,數據科學和圖書館創建中至關重要。

Python的單位測試是什麼?Python的單位測試是什麼?Apr 30, 2025 pm 02:05 PM

本文討論了Python中的單位測試,其好處以及如何有效編寫它們。它突出顯示了諸如UNITSEST和PYTEST之類的工具進行測試。

Python中的訪問說明符是什麼?Python中的訪問說明符是什麼?Apr 30, 2025 pm 02:03 PM

文章討論了Python中的訪問說明符,這些說明符使用命名慣例表明班級成員的可見性,而不是嚴格的執法。

Python中的__Init __()是什麼?自我如何在其中發揮作用?Python中的__Init __()是什麼?自我如何在其中發揮作用?Apr 30, 2025 pm 02:02 PM

文章討論了Python的\ _ \ _ Init \ _ \ _()方法和Self在初始化對象屬性中的作用。還涵蓋了其他類方法和繼承對\ _ \ _ Init \ _ \ _()的影響。

python中的@classmethod,@staticmethod和實例方法有什麼區別?python中的@classmethod,@staticmethod和實例方法有什麼區別?Apr 30, 2025 pm 02:01 PM

本文討論了python中@classmethod,@staticmethod和實例方法之間的差異,詳細介紹了它們的屬性,用例和好處。它說明瞭如何根據所需功能選擇正確的方法類型和DA

您如何將元素附加到Python數組?您如何將元素附加到Python數組?Apr 30, 2025 am 12:19 AM

Inpython,YouAppendElementStoAlistusingTheAppend()方法。 1)useappend()forsingleelements:my_list.append(4).2)useextend()orextend()或= formultiplelements:my_list.extend.extend(emote_list)ormy_list = [4,5,6] .3)useInsert()forspefificpositions:my_list.insert(1,5).beaware

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能