如何设置django 1.8来使用jinja2? [英] How to setup django 1.8 to use jinja2?

查看:326
本文介绍了如何设置django 1.8来使用jinja2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,现在django正式支持Jinja 2作为模板引擎,我希望启用它会像在config中切换一行一样简单。但是当我这样做的时候,jinja找不到我的模板。



我的理解是我可以手动配置一个目录列表来查找模板,但我希望它的行为与DTL的行为默认情况一样。
(即查看/ templates目录)。基本上,我的应用程序的结构是在官方教程中的建议,我想使用jinja而不改变任何其他。这是可能吗?



以下是我的setings.py文件现在的样子:

  TEMPLATES = [
{
'BACKEND':'django.template.backends.jinja2.Jinja2',
'APP_DIRS':True,
},
]

我得到的错误是 TemplateDoesNotExist at /



这里是我的目录结构:

  mysite 
mysite
myapp
模板
myapp
index.html
manage.py

请注意,我希望不要使用任何外部模块。



编辑: as请求,这里是调用模板的代码:

  def index(request):
return render(request,'myapp /index.html')


解决方案

Jinja模板文件夹app dirs默认为 jinja2 不是标准的模板文件夹。



所以尝试以下目录结构,Django将找到您的Jinja模板:

  mysite 
mysite
myapp
jinja2
myapp
index.html
manage.py
/ pre>

So, now that django officially supports Jinja 2 as a templating engine, I hoped enabling it would be as simple as switching a line in config. But when I do that, jinja fails to find my templates.

My understanding is I could manually configure a list of directories for it to look for templates in, but I would like it to behave exactly like DTL behaves by default. (ie. look in the /templates directory). Basically, my app is structured the way it is suggested in the official tutorial, and I would like to use jinja without changing anything else. Is it possible?

Here's how my setings.py file looks now:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'APP_DIRS': True,
    },
]

The error I get is TemplateDoesNotExist at /

and here is my directory structure:

mysite
    mysite
    myapp
        templates
            myapp  
                index.html
    manage.py

please note that I am hoping not to use any external modules.

edit: as requested, here's the code calling the template:

def index(request):
    return render(request, 'myapp/index.html')

解决方案

The Jinja template folder for app dirs defaults to jinja2 not the standard templates folder.

So try the following directory structure and Django will locate your Jinja templates:

mysite
    mysite
    myapp
        jinja2
            myapp  
                index.html
    manage.py

这篇关于如何设置django 1.8来使用jinja2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆