django模板文件路徑設(shè)置

首先在settings.py文件中配置:

網(wǎng)站建設(shè)哪家好,找成都創(chuàng)新互聯(lián)!專注于網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、小程序定制開發(fā)、集團企業(yè)網(wǎng)站建設(shè)等服務(wù)項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了荊州免費建站歡迎大家使用!

TEMPLATES = [

    {

        'BACKEND': 'django.template.backends.django.DjangoTemplates',

        'DIRS': [os.path.join(BASE_DIR, 'templates')],

        'APP_DIRS': True,

        'OPTIONS': {

            'context_processors': [

                'django.template.context_processors.debug',

                'django.template.context_processors.request',

                'django.contrib.auth.context_processors.auth',

                'django.contrib.messages.context_processors.messages',

            ],

        },

    },

]

BACKEND:模板引擎類的python路徑,內(nèi)置的模板引擎分別有'django.template.backends.django.DjangoTemplates'和'django.template.backends.jinja2.Jinja2'

DIRS:模板引擎搜索模板的路徑,如上,默認(rèn)搜索project目錄下的templates目錄

APP_DIRS:告訴模板引擎是否搜索app目錄下的templates目錄。默認(rèn)為true,即是默認(rèn)搜索app目錄下的templates目錄

'DIRS': [os.path.join(BASE_DIR, 'templates')]  是指到  BASE_DIR/templates文件夾中去取模板

'DIRS': [os.path.join(BASE_DIR, 'app1/templates')] 是指到  BASE_DIR/app1/templates文件夾中去取模板

模板文件查找順序

如果同時設(shè)置

'DIRS': [os.path.join(BASE_DIR, 'templates')],

'APP_DIRS': True,

并且同時存在

mysite\templates\polls\index.html

mysite\polls\templates\polls\index.html

則會訪問 mysite\templates\polls\index.html 而不是 mysite\polls\templates\polls\index.html

模板文件的命名空間(其實質(zhì)是模板文件的本地相對路徑)的應(yīng)用場景是,在每個APP下建立appname/templates/appname/,然后在該目錄下再放模板文件(index.html)。然后在需要引用模板文件的地方,采用模板文件相對地址硬編碼時,形式如下:appname/index.html.

例如在views.py中

def index(request):
     #return HttpResponse("Hello, world. You're at the polls index.")
     return render(request,'polls/index.html')

或者index.html中

<li><ahref="/polls/xxx.html">{{question.question_text}}</a></li>

這根URL命名空間不一樣:URL命名空間是用于模板文件中對URL(所謂URL是瀏覽器訪問時的網(wǎng)絡(luò)地址)的反向引用,一般會使用模板標(biāo)簽{% url %}

例如在index.html中

{% url 'polls:detail' question.id %}"

分享名稱:django模板文件路徑設(shè)置
分享網(wǎng)址:http://muchs.cn/article42/ijdghc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、企業(yè)建站、定制網(wǎng)站、品牌網(wǎng)站制作網(wǎng)站排名、建站公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站建設(shè)網(wǎng)站維護公司