最近在学习Django,打算玩玩网页后台方面的东西,因为一直很好奇但却没怎么接触过。Django对我来说是一个全新的内容,思路想来也是全新的,或许并不能写得很明白,所以大家就凑合着看吧~

  本篇笔记(其实我的所有笔记都是),并不会过于详细的讲解。因此如果有大家看不明白的地方,欢迎在我正版博客下留言,有时间的时候我很愿意来这里与大家探讨问题。(当然,不能是简简单单就可以百度到的问题-.-)

  我所选用的教材是《The Django Book 2.0》,本节是第九章,模板高级进阶。


  本节书中内容仅是参考,更多是按照文档中内容来介绍。

  主要是因为书中版本过时,很多代码恰好是1.8中更新的内容,因此只得直接看文档了。


 

0. 目录

  1. RequestContext函数和context处理器

  2. html自动转义

  3. Django如何加载模板

    3.1 什么是Engine

    3.2 加载模板的语句

    3.3 模板加载器

 

1. RequestContext函数和context处理器

  首先,我们回顾模板的视图函数如何书写:

from django.shortcuts import render_to_response

def diary(request):
    return render_to_response('diary.html', {'name': 'qiqi'})

  为了说明方便,我们同时给出另一种写法:

from django.http import HttpResponse
from django.template import loader, Context

def diary(request):
    t = loader.get_template('diary.html')
    c = Context({'name': 'qiqi'})
    return HttpResponse(t.render(c))

  或许还是有同学看不懂,那我就再给出第三种最笨的等价写法,大家大可略过直接往后看:

from django.http import HttpResponse
from django.template import Template, Context

def diary(request):
    tin = open('./templates/diary.html')
    html = tin.read()
    tin.close()

    inf = {'name': 'qiqi'}

    t = Template(html)
    c = Context(inf)
    return HttpResponse(t.render(c))
View Code

相关文章:

  • 2021-06-20
  • 2022-01-01
  • 2021-09-11
  • 2021-12-09
  • 2021-08-31
  • 2021-11-20
  • 2020-01-10
  • 2021-12-14
猜你喜欢
  • 2022-12-23
  • 2021-12-10
  • 2022-02-03
  • 2022-12-23
  • 2021-11-16
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案