Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在Django 1.8中使用jinja2作为模板引擎_Python_Django_Jinja2 - Fatal编程技术网

Python 如何在Django 1.8中使用jinja2作为模板引擎

Python 如何在Django 1.8中使用jinja2作为模板引擎,python,django,jinja2,Python,Django,Jinja2,我一直在研究如何在django 1.8中使用jinja2,但是没有完整的源代码将django与jinja2一起使用。我想知道你们是否知道在django使用jinja2的过程。我已经阅读了官方文件,并研究了以下问题: 但他们都没有清楚地解释如何以一种综合的方式使用jinja2。我刚开始使用django,不知道文档中的所有行话。非常感谢您的帮助。settings.py中的Django(请查看此内容以获得进一步指导): TEMPLATES = [ { 'BACKEND': 'd

我一直在研究如何在django 1.8中使用jinja2,但是没有完整的源代码将django与jinja2一起使用。我想知道你们是否知道在django使用jinja2的过程。我已经阅读了官方文件,并研究了以下问题:

但他们都没有清楚地解释如何以一种综合的方式使用jinja2。我刚开始使用django,不知道文档中的所有行话。非常感谢您的帮助。
settings.py中的Django(请查看此内容以获得进一步指导)

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            # ... some options here ...
        },
    },
]
from django.template.loader import get_template
from django import template
register = template.Library()

@register.simple_tag(takes_context=True)
def jinja_include(context, filename):
    template = get_template(filename)
    return template.render(context.flatten())
后端是实现Django的模板后端API的模板引擎类的点式Python路径。内置后端是django.template.backends.django.DjangoTemplates和django.template.backends.jinja2.jinja2


基本上找出settings.py文件中的模板变量,并设置后端(或确保后端)与上面的类似(因为Jinga是内置的)。如果全部失败,请将
django.template.backends…
替换为
django.template.backends.jinja2.jinja2
(尽管我认为没有必要)

首先您必须安装
jinja2

$ pip install Jinja2
然后修改
设置.py中的
模板
列表,以包含
jinja2
后端

TEMPLATES = [

    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'DIRS': [os.path.join(BASE_DIR, 'templates/jinja2')],
        'APP_DIRS': True,
        'OPTIONS': {'environment': 'myproject.jinja2.Environment',}, 
    },
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
           ],
        },
    },
]
其中
templates/jinja2
是包含jinja2模板文件的目录

在views.py文件中:

from __future__ import absolute_import  # Python 2 only
from jinja2 import Environment
from django.contrib.staticfiles.storage import staticfiles_storage
from django.urls import reverse

def environment(**options):
    env = Environment(**options)
    env.globals.update({
       'static': staticfiles_storage.url,
       'url': reverse,
    })
    return env
这使得Jinja2模板中的
静态
url
可用


p.S.有关更多详细信息,请参见。

混合Django和Jinja2模板:环境:Django 1.8+Jinja2

我有一些传统的Django模板,一次将它们全部重写到Jinja2并不容易,所以将这个自定义的
{%jinja\u包括“some_template.jinja”%}
标记添加到
my_custom\u tags.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            # ... some options here ...
        },
    },
]
from django.template.loader import get_template
from django import template
register = template.Library()

@register.simple_tag(takes_context=True)
def jinja_include(context, filename):
    template = get_template(filename)
    return template.render(context.flatten())
从Django模板中这样称呼它:

{% load my_custom_tags %}
{% jinja_include "some_template.jinja" %}

我花了很长时间才弄明白,这里的答案并没有那么有用

多鲁的回答最接近事实,但并不完整

如何使用jinja作为模板语言:

1.在项目文件夹中创建jinja2.py文件。这是修改默认jinja2环境所必需的(在我们的例子中,传递一些额外的全局变量)

位置:
{root}/main/jinja2.py:

from __future__ import absolute_import  # Python 2 only
from jinja2 import Environment
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse

def environment(**options):
    env = Environment(**options)
    env.globals.update({
       'static': staticfiles_storage.url,
       'url': reverse,
    })
    return env
2.将jinja2后端添加到django项目设置文件,包括我们修改的环境

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'environment': "main.jinja2.environment",
        },
    },
    ...
]
3.现在您不再需要在任何地方导入jinja2,在您的视图中,您将通过django使用jinja模板,就像django模板一样:

from django.shortcuts import render

def index(request, **kwargs):
    return render(request, "index.html.j2", {'title': 'MyTitle', 'text': "MyText"})
最后,当APP_DIRS设置为True时,jinja将在所有安装的APP
jinja2
目录中搜索模板。(与搜索
模板
文件夹的DTL不同)。如果您想要改变这种行为,或者想要一些额外的调整,比如扩展匹配、过滤或全局变量,您应该看看django-jinja扩展


您还可以通过设置的
templates['DIRS']
选项提供额外的目录来搜索模板。

我们如何添加上下文处理器?根据Jinja2的
APP\u DIRS
,不建议将上下文处理器与Jinja2模板一起使用。在设置中,您可以将环境配置为
myproject.jinja2.environment
,但应该改用
myproject.jinja2.environment
(小写“e”)。前者加载内置环境类,该类不包含自定义函数“static”和“url”。django模板语言是django模板api?@wkcamp问题在于设置“BACKEND”:“django.template.backends.jinja2.jinja2”。“你的回答有误导性。”德尼斯特罗菲莫夫,我三年前写了这个答案。我的答复首先应该被认为是过时和不相关的,因为它被张贴的日期和收到的选票不足。如果你忽略了这一点,那么是的,它不能回答问题。❝Django 2.0删除了Django.core.urlResolver模块,该模块在1.10版中被移动到了Django.urls。您应该将任何导入更改为使用django.url。❞ 看见