Django——模板—模板位置+模板的渲染

  1. 模板位置


    # 在应用中建templates目录,好处不需要注册,有多个应用的时候不能复用
    # 第2种是放在工程的目录下,如果有多个应用,可以调用相同的页面,
    # 需要注册
    # 需要修改项目的配置文件settings.py
    
    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',
                ],
            },
        },
    ]
    
    # Django 模板查找机制: Django 查找模板的过程是在每个 app 的 templates文件夹中找(不只是当前 #app 中的代码只在当前的 app 的 templates 文件夹中找)。

     

  2. 模板的渲染


    # 1 loader加载
    # 好处是可以加载1次模板,然后多次渲染
    from django.template import loader  # 导⼊loader
    
    
    def index(request):
        temp = loader.get_template('index.html')
        print(temp.__dict__)
        # 渲染模板,html源码
        res = temp.render(context={'content': 'hello index'})
        print(res)
        return HttpResponse(res)
    
    # 2 render
    from django.shortcuts import render
        render(request,templatesname,context=None)
    # 参数:
    #  request: 请求对象
    #  templatesname:模板名称
    #  context:参数字典,必须是字典

     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值