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

时间:2022-08-14 20:47:30

I have been looking on how to use jinja2 in django 1.8, but there is no complete source for using django with jinja2. I was wondering if you guys knew the process for using jinja2 in django. I have looked through the the official documentation and I have looked at the following question: How to setup django 1.8 to use jinja2?

我一直在研究如何在django 1.8中使用jinja2,但是没有完整的源代码可以使用jinja2来使用django。我想知道你们是否知道在django使用jinja2的过程。我已经查看了官方文档,并查看了以下问题:如何设置django 1.8来使用jinja2?

but none of them clearly explain how to use jinja2 in an put-togther manner. I just started using django and don't know all the lingo in the docs. I would really appreciate the help.

但是,没有一个人清楚地解释了如何使用jinja2的方式。我刚开始使用django,不知道文档中所有的术语。我真的很感激你的帮助。

4 个解决方案

#1


21  

Frist you have to install jinja2:

你必须安装jinja2:

$ pip install Jinja2

Then modify your TEMPLATES list in the settings.py to contain the jinja2 BACKEND :

然后在设置中修改您的模板列表。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',
           ],
        },
    },
]

where templates/jinja2 is the directory with your jinja2 template files.

其中模板/jinja2是您的jinja2模板文件的目录。

And in your views.py file:

和你的观点。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

This makes static and url available in your Jinja2 templates.

这使得Jinja2模板中可以使用静态和url。

P.S. For more details see this article.

有关更多细节,请参阅本文。

#2


6  

Took me quite some time to figure out everything, answers here weren't all that helpful.

花了很长时间才弄明白,这里的答案并不是很有帮助。

doru's answer is closest to truth but is incomplete.

多鲁的答案与真理最接近,但并不完整。

How to use jinja as templating language:

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

1.Create jinja2.py file in your project folder. This is required to modify the default jinja2 Environment (in our case, passing some additional global variables).

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

location: {root}/main/jinja2.py:

地点:{根} /主/ 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.Add jinja2 backend to django project settings file, including our modified environment.

2。添加jinja2后端到django项目设置文件,包括我们的修改环境。

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'environment': "main.jinja2.environment",
        },
    },
    ...
]

3.Now you no longer need to import jinja2 anywhere, in your views, you will be using jinja templates through django just like django templates:

3所示。现在您不再需要在任何地方导入jinja2,在您的视图中,您将通过django使用jinja模板,就像django模板一样:

from django.shortcuts import render

def index(request, **kwargs):
    return render(request, "index.html.j2", {'title': 'MyTitle', 'text': "MyText"})

And finally, with APP_DIRS set to True jinja will search templates in all installed apps jinja2 directories. (unlike DTL that searches for templates folder). If you want to change that behavior, or want some extra tweaking, like extension match, filtering or global variables, you should look at django-jinja extension.

最后,将APP_DIRS设置为True jinja,将在所有已安装的应用程序jinja2目录中搜索模板。(不像DTL搜索模板文件夹)。如果您想要改变这种行为,或者需要一些额外的调整,比如扩展匹配、过滤或全局变量,您应该看看django-jinja扩展。

You may also provide additional directories to search for templates via TEMPLATES['DIRS'] option of settings.

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

#3


1  

From the Django website (please look at this for further guidance) in settings.py:

从Django的网站(请查看这个以获得进一步的指导)在设置。py:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            # ... some options here ...
        },
    },
]

BACKEND is a dotted Python path to a template engine class implementing Django’s template backend API. The built-in backends are django.template.backends.django.DjangoTemplates and django.template.backends.jinja2.Jinja2.

后端是一个用于实现Django模板后端API的模板引擎类的星形Python路径。内置的后端是django.template.backends.django。DjangoTemplates django.template.backends.jinja2.Jinja2。

Basically find out where in your settings.py file there is a TEMPLATES variable and set the backend (or make sure the backend) resembles the one above (as Jinga is built-in). If all fails, replace the django.template.backends... with django.template.backends.jinja2.Jinja2 (though I don't think that is necessary).

基本上找出你的设置在哪里。py文件有一个模板变量,并设置后端(或确保后端)类似于上面的那个(正如Jinga内置的)。如果都失败了,就替换掉django.template.backends。django.template.backends.jinja2。Jinja2(虽然我不认为这是必要的)。

#4


1  

Mixed Django and Jinja2 Template: Environment: Django 1.8 + Jinja2.

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

I have some legacy Django templates and it's not so easy to rewrite them all at once to Jinja2, so add this custom {% jinja_include "some_template.jinja" %} tag to my_custom_tags.py:

我有一些遗留的Django模板,并不是很容易将它们全部重写到Jinja2,所以添加这个自定义的{% jinja_include“some_template”。jinja“%}标签到my_custom_tags.py:

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())

Call it like this from your Django template:

从Django模板调用它:

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

#1


21  

Frist you have to install jinja2:

你必须安装jinja2:

$ pip install Jinja2

Then modify your TEMPLATES list in the settings.py to contain the jinja2 BACKEND :

然后在设置中修改您的模板列表。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',
           ],
        },
    },
]

where templates/jinja2 is the directory with your jinja2 template files.

其中模板/jinja2是您的jinja2模板文件的目录。

And in your views.py file:

和你的观点。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

This makes static and url available in your Jinja2 templates.

这使得Jinja2模板中可以使用静态和url。

P.S. For more details see this article.

有关更多细节,请参阅本文。

#2


6  

Took me quite some time to figure out everything, answers here weren't all that helpful.

花了很长时间才弄明白,这里的答案并不是很有帮助。

doru's answer is closest to truth but is incomplete.

多鲁的答案与真理最接近,但并不完整。

How to use jinja as templating language:

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

1.Create jinja2.py file in your project folder. This is required to modify the default jinja2 Environment (in our case, passing some additional global variables).

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

location: {root}/main/jinja2.py:

地点:{根} /主/ 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.Add jinja2 backend to django project settings file, including our modified environment.

2。添加jinja2后端到django项目设置文件,包括我们的修改环境。

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'environment': "main.jinja2.environment",
        },
    },
    ...
]

3.Now you no longer need to import jinja2 anywhere, in your views, you will be using jinja templates through django just like django templates:

3所示。现在您不再需要在任何地方导入jinja2,在您的视图中,您将通过django使用jinja模板,就像django模板一样:

from django.shortcuts import render

def index(request, **kwargs):
    return render(request, "index.html.j2", {'title': 'MyTitle', 'text': "MyText"})

And finally, with APP_DIRS set to True jinja will search templates in all installed apps jinja2 directories. (unlike DTL that searches for templates folder). If you want to change that behavior, or want some extra tweaking, like extension match, filtering or global variables, you should look at django-jinja extension.

最后,将APP_DIRS设置为True jinja,将在所有已安装的应用程序jinja2目录中搜索模板。(不像DTL搜索模板文件夹)。如果您想要改变这种行为,或者需要一些额外的调整,比如扩展匹配、过滤或全局变量,您应该看看django-jinja扩展。

You may also provide additional directories to search for templates via TEMPLATES['DIRS'] option of settings.

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

#3


1  

From the Django website (please look at this for further guidance) in settings.py:

从Django的网站(请查看这个以获得进一步的指导)在设置。py:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            # ... some options here ...
        },
    },
]

BACKEND is a dotted Python path to a template engine class implementing Django’s template backend API. The built-in backends are django.template.backends.django.DjangoTemplates and django.template.backends.jinja2.Jinja2.

后端是一个用于实现Django模板后端API的模板引擎类的星形Python路径。内置的后端是django.template.backends.django。DjangoTemplates django.template.backends.jinja2.Jinja2。

Basically find out where in your settings.py file there is a TEMPLATES variable and set the backend (or make sure the backend) resembles the one above (as Jinga is built-in). If all fails, replace the django.template.backends... with django.template.backends.jinja2.Jinja2 (though I don't think that is necessary).

基本上找出你的设置在哪里。py文件有一个模板变量,并设置后端(或确保后端)类似于上面的那个(正如Jinga内置的)。如果都失败了,就替换掉django.template.backends。django.template.backends.jinja2。Jinja2(虽然我不认为这是必要的)。

#4


1  

Mixed Django and Jinja2 Template: Environment: Django 1.8 + Jinja2.

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

I have some legacy Django templates and it's not so easy to rewrite them all at once to Jinja2, so add this custom {% jinja_include "some_template.jinja" %} tag to my_custom_tags.py:

我有一些遗留的Django模板,并不是很容易将它们全部重写到Jinja2,所以添加这个自定义的{% jinja_include“some_template”。jinja“%}标签到my_custom_tags.py:

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())

Call it like this from your Django template:

从Django模板调用它:

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