您的位置:首页 > 编程语言 > Go语言

用jinja2替换Django的模板

2013-04-16 11:40 288 查看
整个项目的文件结构如下:

~/hg_repo/Django/Django$ tree

.├── index.py├── __init__.py├── jobs│ ├── __init__.py│ ├── models.py│ ├── templates│ │ ├── __init__.py│ │ ├── job_base.html│ │ └── job_list.html│ ├── tests.py│ ├── urls.py│ ├── views.py├── settings.py├── templates│ ├── base.html│ └── index.html├── urls.py└── wsgi.py
jobs是一个application,index.py是首页入口,项目下的templates目录放全局template,包括首页index.html及公共模板base.html。

首先,Django的模板查找顺序在项目的settings.py定义:

TEMPLATE_LOADERS = (

'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader',# 'django.template.loaders.eggs.Loader',)
以上设置表明先从文件目录找,如果找不到就从每个application下的templates文件夹下找。

而文件目录又是如下定义:

TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'/home/andrew/hg_repo/Django/Django/templates',)
jobs中使用jinja2的模板,views.py代码如下:

from django.http import HttpResponsefrom django.conf import settingsfrom jinja2 import Environment, PackageLoader, FileSystemLoader, ChoiceLoaderfrom Django.jobs.models import Jobdef job_list(request): loader = ChoiceLoader([ FileSystemLoader(settings.TEMPLATE_DIRS), PackageLoader('Django.jobs', 'templates') ]) env = Environment(loader=loader) template = env.get_template('job_list.html') object_list = Job.objects.all() return HttpResponse( template.render(object_list=object_list) )
ChoiceLoader根据顺序找模板,原理和Django的TEMPLATE_LOADERS类似,加FileSystemLoader(settings.TEMPLATE_DIRS)的目的是为了找到项目的templates
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: