Django笔记-Template

django1.6.1中如果在app下新建立了templates目录,必须重新启动server,否则不会被识别

 

1.模板构成

模板动态部分由tags({% if %}) 和variables{{ var }}两部分
context用来给template传递数据的,是一种类似字典的name->value的映射数据。

2.RequestContext
为什么要用RequestContext?
代码来回答:
例子1:
from django.template import loader, Context

from django.shortcuts import render_to_response

def view_1(request):
 ....
 t = loader.get_template('template1.html')
 c = Context({
  'app':'My app',
  'user':request.user,
  'ip_address':request.META['REMOTE_ADDR'],
  'message':'I am view 1.'
  })
  return t.render_to_response(c)
  
def view_2(request):
 #...
 t = loader.get_template('template2.html')
 c = Context({
  'app':'My app',
  'user':request.user
  'ip_address':request.META['REMOTE_ADD'],
  'message':'I am the second view.'
  })
 return t.render_to_response(c)
 
可以看出,如果有类似的多个C,那么每次都需要重新写一下。
RequestContext可以帮你完成这个问题。修改后代码如下

def comm_proc(request):
 return {
  'app':'My app',
  'user':request.user,
  'ip_address':request.META['REMOTE_ADDR'],
  'message':'I am view sdf.'
  }

def view_1(request):
 return render_to_response("exercise/template.html", RequestContext(request,processors=[comm_proc]))

 

3. RequestContext好处

在django.conf.global_setting.py中有定义的默认的processor
参见变量TEMPLATE_CONTEXT_PROCESSORS
默认设置有:
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
)


你可以在setting中设置为本站所有的requestContext公用的processor
TEMPLATE_CONTEXT_PROCESSORS

如果在setting中定义了TEMPLATE_CONTEXT_PROCESSORS,则django.conf.global_setting.py中的该变量就会失效。
注意:定义在TEMPLATE_CONTEXT_PROCESSORS中的processor,在每个模板中都会被用到,
所以,如果你想用摸个模板来渲染requestContext那么请注意变量名字别重复(大小写区分)

context_processor推荐放置文件文件名context_processors.py中。

 

4.Automatic HTML Escaping

Django模板会自动回避到一些关键的符号,尤其是<,>,'',&等特殊符号。
所以用Django模板不用自己特殊处理这些。

但是随之带来的问题是有些可信的html也会被回避,比如发送Email等时,不
想被回避。解决办法如下
1)单个变量回避用safe过滤器
This will not be escaped: {{ data|safe }}
这里如果data值为:<script>alter("hello")</script>加上safe过滤器后就会
弹出对话框,如果不加,则会被Django模板给escape掉。
2)块注释
{% autoescape off %}
 Hello {{name}}
{% endautoescape %}
这里autoscape off和autoscape on是可以嵌套的。


5. Inside Template Loading
通常,用户可以通过TEMPLATE_DIR来制定模板在操作系统中存放的位置(可以放在系统中的任意位置),
另一种更方面方法时用户可以定制模板加载器来加载模板,
两种load模板方法:
1)  django.template.loader.get_template(template_name)
2)  django.template.loader.select_template(template_name_list):
select_template is just like get_template, except it takes a list of template names.
Of the list, it returns the first template that exists. If none of the templates exist,
 
三种加载器(TEMPLATE_LOADERS):加载器按照在TEMPLATE_LAODERS中的顺序排优先级。
1)  django.template.loaders.filesystem.load_template_source
该加载器从文件系统中加载模板,也就是TEMPLATE_DIRS中定义的部分。

2)  django.template.loaders.app_directories.load_template_source
从加载器的名字就可以看出,该加载器可以按照app_directories来自动查找模板,
该加载器是非常方便的。只要在安装的app(INSTALLED_APP中注册过)中注册过,
该加载器就会在第一次启动时查找对应app目录下是否有templates目录,如果有则会将该目录下模板加载。
For example, if INSTALLED_APPS contains ('myproject.polls',), then get_template('foo.html')
 will look for templates:
/path/to/myproject/polls/templates/foo.html

3)  django.template.loaders.eggs.load_template_source
该加载器从python eggs中加载模板,默认关闭。若app时通过eggs发布时需要打开。

 

6 .Creating a Template Library
Django允许用户创建自己的模板库,包括创建标签和过滤器,
同样,也可以创建自己的加载器,这些功能是十分强大的,以后用到时需要仔细研究下。
django框架模板也是这么实现的,可以参见。
django/template/defaultfilters.py and django/template/defaulttags.py

7 .可以用include在模板中包含其他模板

 <body>
{% include "includes/nav.html" %}
<h1>{{ title }}</h1>
</body>

7 .可以用模板继承的方法来更加简化代码

<本节完>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Django是一个用于快速开发Web应用程序的Python Web框架。而python-docx-template是一个Python库,它可以使用Word文档作为模板,然后根据传入的数据批量生成Word文档。在Django中,我们可以利用python-docx-template库来实现批量生成Word文档的功能。 首先,我们需要在Django项目中安装python-docx-template库。可以使用pip命令来安装该库: ```bash pip install python-docx-template ``` 接下来,我们可以在Django项目中创建一个视图函数,用于接收数据并根据模板生成Word文档。在视图函数中,我们可以使用python-docx-template库提供的方法将数据填充到Word模板中,生成最终的Word文档。 例如,假设我们有一个Word文档模板`template.docx`,里面包含了一些需要填充数据的位置,我们可以在Django中这样写视图函数: ```python from docxtpl import DocxTemplate from django.http import HttpResponse def generate_word_document(request): # 从请求中获取数据 data = request.GET.get('data', '') # 读取Word模板 doc = DocxTemplate("template.docx") # 根据数据填充模板 context = {'data': data} doc.render(context) # 写入生成的Word文档 doc.save("generated_document.docx") # 返回生成的Word文档给用户 with open("generated_document.docx", 'rb') as f: response = HttpResponse(f.read(), content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename=generated_document.docx' return response ``` 通过上述视图函数,我们可以在Django项目中实现批量生成Word文档的功能,用户可以通过传入数据来生成他们所需的Word文档。这样我们就可以方便地利用Python和Django来批量生成Word文档,提高生产效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值