第二章:Django模板的渲染

一、django中配置html模板路径的方式有

都是在项目文件的settings.py中配置

  • 1、使用相对路径(常用)

    'DIRS': ['templates']
  • 2、使用绝对路径

    'DIRS': ['F:/workTest/python/django/firstproject/templates'],
  • 3、使用OS模块查找路径(使用pycharm创建django项目就是这个)

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

二、渲染模板的方式

  • 1、直接使用render渲染(常用且安全方式)[默认导包]

    def index1(request):
        return render(request,'book1.html')
  • 2、使用render_to_response渲染模版[需要导入包]

    from django.shortcuts import render,render_to_response
    def index3(request):
        return render_to_response('book.html')
  • 3、使用render_to_string渲染模版[需要导包]

    from django.http import HttpResponse
    from django.template.loader import render_to_string
    def index4(request):
        html = render_to_string('book1.html')
        return HttpResponse(html)
  • 4、使用get_template渲染模版[需要导包]

    from django.http import HttpResponse
    from django.template.loader import get_template,render_to_string
    def index5(request):
        t = get_template('book.html')
        html = t.render({})
        return HttpResponse(html)

三、在自己创建的组件(app)下创建一个templates文件夹存放当前组件下的模块

  • 1、settings.py文件夹下的设置'APP_DIRS': True,(默认就是true)
  • 2、在settings.py中添加自己创建的组件(app)

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'book'
    ]
  • 3、在组件下创建templates文件夹

  • 4、渲染方式跟上面一样的

总结一般我们模版文件不会放在组件(app)里面,如果放在里面就不需要配置'DIRS': ['templates']

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水痕01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值