django_templatess使用

templates

​ Django自带的是DTL(Django Templates language)
​ DTL模版是一种带有特殊语法的HTML文件。

渲染模版方式有两种

方式1:

 render_to_string()找到模版,然后将模版编译后渲染成Python的字符串格式。
最后再通过HttpResource类包装成一个HttpResponse对象返回

from django.template.loader import render_to_string
from django.http import HttpResponse

def return_page(request):
    html = render_to_string("login.html")
    return HttpResponse(html)

方式2:
render()直接将模板渲染称字符串和包装成HttpResponse对象一步到位完成。

from django.shortcuts import render
from django.http import HttpResponse

def return_page(request):
    return render(request, "login.html")
  
render_to_response将被render取代,功能一致

模版查找路径

在setting.py中查看

# 该配置包含了模板引擎的配置、模板查找路径的配置、模板上下文的配置等。
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')] #自定义templates文件夹的绝对路径
        ,
        'APP_DIRS': True, # 注意 开启App内查找templates文件夹下的html
        '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',
            ],
        },
    },
]


模板查找路径
    DIRS:一个列表,存放所有的模板路径。
    APP_DIRS :默认为True,为True时,会在INSTALLED_APP已安装的APP下的
templates文件夹(注意文件夹名一定是templates)中查找模板
        如果为False,就只在DIRS中查找

模板查找顺序
    会先在DIRS这个列表中一次找到路径下有无该模板,如果有,则返回
    如果
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值