如何在不使用Django其余部分的情况下使用Django模板?

时间:2021-11-03 06:13:24

I want to use the Django template engine in my (Python) code, but I'm not building a Django-based web site. How do I use it without having a settings.py file (and others) and having to set the DJANGO_SETTINGS_MODULE environment variable?

我想在我的(Python)代码中使用Django模板引擎,但是我不是在构建一个基于djangol的web站点。如何在没有设置的情况下使用它。py文件(和其他文件)和必须设置DJANGO_SETTINGS_MODULE环境变量?

If I run the following code:

如果我运行以下代码:

>>> import django.template
>>> from django.template import Template, Context
>>> t = Template('My name is {{ my_name }}.')

I get:

我得到:

ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

13 个解决方案

#1


130  

The solution is simple. It's actually well documented, but not too easy to find. (I had to dig around -- it didn't come up when I tried a few different Google searches.)

解决方案是简单。它实际上有很好的文献记载,但不是很容易找到。(我不得不四处寻找——当我尝试了谷歌上的不同搜索时,它并没有出现。)

The following code works:

下面的代码:

>>> from django.template import Template, Context
>>> from django.conf import settings
>>> settings.configure()
>>> t = Template('My name is {{ my_name }}.')
>>> c = Context({'my_name': 'Daryl Spitzer'})
>>> t.render(c)
u'My name is Daryl Spitzer.'

See the Django documentation (linked above) for a description of some of the settings you may want to define (as keyword arguments to configure).

参见Django文档(链接在上面),了解您可能要定义的一些设置的描述(作为要配置的关键字参数)。

#2


40  

Jinja2 syntax is pretty much the same as Django's with very few differences, and you get a much more powerfull template engine, which also compiles your template to bytecode (FAST!).

Jinja2的语法与Django的语法非常相似,但差异非常小,并且您得到了一个更强大的模板引擎,它也将您的模板编译成字节码(FAST!)。

I use it for templating, including in Django itself, and it is very good. You can also easily write extensions if some feature you want is missing.

我将它用于模板,包括Django本身,它非常好。如果您想要的某些特性丢失了,您也可以轻松地编写扩展。

Here is some demonstration of the code generation:

下面是代码生成的一些演示:

>>> import jinja2
>>> print jinja2.Environment().compile('{% for row in data %}{{ row.name | upper }}{% endfor %}', raw=True) 
from __future__ import division
from jinja2.runtime import LoopContext, Context, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_join
name = None

def root(context, environment=environment):
    l_data = context.resolve('data')
    t_1 = environment.filters['upper']
    if 0: yield None
    for l_row in l_data:
        if 0: yield None
        yield unicode(t_1(environment.getattr(l_row, 'name')))

blocks = {}
debug_info = '1=9'

#3


9  

Any particular reason you want to use Django's templates? Both Jinja and Genshi are, in my opinion, superior.

您想使用Django的模板有什么特别的原因吗?在我看来,金印和源氏都是优越的。


If you really want to, then see the Django documentation on settings.py. Especially the section "Using settings without setting DJANGO_SETTINGS_MODULE". Use something like this:

如果您确实需要,那么请查看关于settings.py的Django文档。特别是“使用设置而不设置DJANGO_SETTINGS_MODULE”的部分。使用这样的:

from django.conf import settings
settings.configure (FOO='bar') # Your settings go here

#4


7  

I would also recommend jinja2. There is a nice article on django vs. jinja2 that gives some in-detail information on why you should prefere the later.

我也推荐jinja2。有一篇关于django和jinja2的很好的文章,它提供了一些详细的信息,说明为什么您应该选择后面的文章。

#5


3  

According to the Jinja documentation, Python 3 support is still experimental. So if you are on Python 3 and performance is not an issue, you can use django's built in template engine.

根据Jinja文档,Python 3支持仍处于试验阶段。因此,如果您使用的是Python 3,并且性能不是问题,您可以使用django的内置模板引擎。

Django 1.8 introduced support for multiple template engines which requires a change to the way templates are initialized. You have to explicitly configure settings.DEBUG which is used by the default template engine provided by django. Here's the code to use templates without using the rest of django.

Django 1.8引入了对多个模板引擎的支持,这些引擎需要更改模板初始化的方式。您必须显式地配置设置。由django提供的默认模板引擎使用的调试。下面是使用模板而不使用django其余部分的代码。

from django.template import Template, Context
from django.template.engine import Engine

from django.conf import settings
settings.configure(DEBUG=False)

template_string = "Hello {{ name }}"
template = Template(template_string, engine=Engine())
context = Context({"name": "world"})
output = template.render(context) #"hello world"

#6


2  

I would say Jinja as well. It is definitely more powerful than Django Templating Engine and it is stand alone.

我也可以说津佳。它肯定比Django模板引擎更强大,而且它是独立的。

If this was an external plug to an existing Django application, you could create a custom command and use the templating engine within your projects environment. Like this;

如果这是现有Django应用程序的外部插件,您可以创建一个自定义命令并在项目环境中使用模板引擎。像这样;

manage.py generatereports --format=html

But I don't think it is worth just using the Django Templating Engine instead of Jinja.

但是我不认为仅仅使用Django模板引擎而不是Jinja是值得的。

#7


2  

Thanks for the help folks. Here is one more addition. The case where you need to use custom template tags.

谢谢你们的帮助。这里还有一个加法。需要使用自定义模板标记的情况。

Let's say you have this important template tag in the module read.py

假设在模块read.py中有这个重要的模板标记

from django import template

register = template.Library()

@register.filter(name='bracewrap')
def bracewrap(value):
    return "{" + value + "}"

This is the html template file "temp.html":

这是html模板文件“temp.html”:

{{var|bracewrap}}

Finally, here is a Python script that will tie to all together

最后,这里有一个Python脚本,它将与所有脚本绑定在一起

import django
from django.conf import settings
from django.template import Template, Context
import os

#load your tags
from django.template.loader import get_template
django.template.base.add_to_builtins("read")

# You need to configure Django a bit
settings.configure(
    TEMPLATE_DIRS=(os.path.dirname(os.path.realpath(__file__)), ),
)

#or it could be in python
#t = Template('My name is {{ my_name }}.')
c = Context({'var': '*.com rox'})

template = get_template("temp.html")
# Prepare context ....
print template.render(c)

The output would be

的输出将是

{*.com rox}

#8


1  

Found this:

发现了这个:

http://snippets.dzone.com/posts/show/3339

http://snippets.dzone.com/posts/show/3339

#9


1  

Don't. Use StringTemplate instead--there is no reason to consider any other template engine once you know about it.

不喜欢。使用StringTemplate代替——一旦您知道了它,就没有理由再考虑任何其他模板引擎了。

#10


1  

An addition to what other wrote, if you want to use Django Template on Django > 1.7, you must give your settings.configure(...) call the TEMPLATES variable and call django.setup() like this :

另外,如果您想在Django > 1.7中使用Django模板,那么必须为您的settings.configure(…)调用模板变量并调用Django .setup()如下所示:

from django.conf import settings

settings.configure(TEMPLATES=[
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['.'], # if you want the templates from a file
        'APP_DIRS': False, # we have no apps
    },
])

import django
django.setup()

Then you can load your template like normally, from a string :

然后你可以像往常一样从字符串中加载模板:

from django import template   
t = template.Template('My name is {{ name }}.')   
c = template.Context({'name': 'Rob'})   
t.render(c)

And if you wrote the DIRS variable in the .configure, from the disk :

如果你在。configure中写入DIRS变量,从磁盘:

from django.template.loader import get_template
t = get_template('a.html')
t.render({'name': 5})

Django Error: No DjangoTemplates backend is configured

Django错误:没有配置DjangoTemplates后端

http://django.readthedocs.io/en/latest/releases/1.7.html#standalone-scripts

http://django.readthedocs.io/en/latest/releases/1.7.html standalone-scripts

#11


0  

I echo the above statements. Jinja 2 is a pretty good superset of Django templates for general use. I think they're working on making the Django templates a little less coupled to the settings.py, but Jinja should do well for you.

我同意上述声明。Jinja 2是一个非常好的Django模板的超集,可用于一般用途。我认为他们正在努力使Django模板与设置少一些耦合。是啊,但是金嘉应该做得很好。

#12


0  

While running the manage.py shell:

在运行管理。py壳:

>>> from django import template   
>>> t = template.Template('My name is {{ me }}.')   
>>> c = template.Context({'me': 'ShuJi'})   
>>> t.render(c)

#13


0  

Google AppEngine uses the Django templating engine, have you taken a look at how they do it? You could possibly just use that.

谷歌AppEngine使用Django模板引擎,您看过它们是如何实现的吗?你可以用这个。

#1


130  

The solution is simple. It's actually well documented, but not too easy to find. (I had to dig around -- it didn't come up when I tried a few different Google searches.)

解决方案是简单。它实际上有很好的文献记载,但不是很容易找到。(我不得不四处寻找——当我尝试了谷歌上的不同搜索时,它并没有出现。)

The following code works:

下面的代码:

>>> from django.template import Template, Context
>>> from django.conf import settings
>>> settings.configure()
>>> t = Template('My name is {{ my_name }}.')
>>> c = Context({'my_name': 'Daryl Spitzer'})
>>> t.render(c)
u'My name is Daryl Spitzer.'

See the Django documentation (linked above) for a description of some of the settings you may want to define (as keyword arguments to configure).

参见Django文档(链接在上面),了解您可能要定义的一些设置的描述(作为要配置的关键字参数)。

#2


40  

Jinja2 syntax is pretty much the same as Django's with very few differences, and you get a much more powerfull template engine, which also compiles your template to bytecode (FAST!).

Jinja2的语法与Django的语法非常相似,但差异非常小,并且您得到了一个更强大的模板引擎,它也将您的模板编译成字节码(FAST!)。

I use it for templating, including in Django itself, and it is very good. You can also easily write extensions if some feature you want is missing.

我将它用于模板,包括Django本身,它非常好。如果您想要的某些特性丢失了,您也可以轻松地编写扩展。

Here is some demonstration of the code generation:

下面是代码生成的一些演示:

>>> import jinja2
>>> print jinja2.Environment().compile('{% for row in data %}{{ row.name | upper }}{% endfor %}', raw=True) 
from __future__ import division
from jinja2.runtime import LoopContext, Context, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_join
name = None

def root(context, environment=environment):
    l_data = context.resolve('data')
    t_1 = environment.filters['upper']
    if 0: yield None
    for l_row in l_data:
        if 0: yield None
        yield unicode(t_1(environment.getattr(l_row, 'name')))

blocks = {}
debug_info = '1=9'

#3


9  

Any particular reason you want to use Django's templates? Both Jinja and Genshi are, in my opinion, superior.

您想使用Django的模板有什么特别的原因吗?在我看来,金印和源氏都是优越的。


If you really want to, then see the Django documentation on settings.py. Especially the section "Using settings without setting DJANGO_SETTINGS_MODULE". Use something like this:

如果您确实需要,那么请查看关于settings.py的Django文档。特别是“使用设置而不设置DJANGO_SETTINGS_MODULE”的部分。使用这样的:

from django.conf import settings
settings.configure (FOO='bar') # Your settings go here

#4


7  

I would also recommend jinja2. There is a nice article on django vs. jinja2 that gives some in-detail information on why you should prefere the later.

我也推荐jinja2。有一篇关于django和jinja2的很好的文章,它提供了一些详细的信息,说明为什么您应该选择后面的文章。

#5


3  

According to the Jinja documentation, Python 3 support is still experimental. So if you are on Python 3 and performance is not an issue, you can use django's built in template engine.

根据Jinja文档,Python 3支持仍处于试验阶段。因此,如果您使用的是Python 3,并且性能不是问题,您可以使用django的内置模板引擎。

Django 1.8 introduced support for multiple template engines which requires a change to the way templates are initialized. You have to explicitly configure settings.DEBUG which is used by the default template engine provided by django. Here's the code to use templates without using the rest of django.

Django 1.8引入了对多个模板引擎的支持,这些引擎需要更改模板初始化的方式。您必须显式地配置设置。由django提供的默认模板引擎使用的调试。下面是使用模板而不使用django其余部分的代码。

from django.template import Template, Context
from django.template.engine import Engine

from django.conf import settings
settings.configure(DEBUG=False)

template_string = "Hello {{ name }}"
template = Template(template_string, engine=Engine())
context = Context({"name": "world"})
output = template.render(context) #"hello world"

#6


2  

I would say Jinja as well. It is definitely more powerful than Django Templating Engine and it is stand alone.

我也可以说津佳。它肯定比Django模板引擎更强大,而且它是独立的。

If this was an external plug to an existing Django application, you could create a custom command and use the templating engine within your projects environment. Like this;

如果这是现有Django应用程序的外部插件,您可以创建一个自定义命令并在项目环境中使用模板引擎。像这样;

manage.py generatereports --format=html

But I don't think it is worth just using the Django Templating Engine instead of Jinja.

但是我不认为仅仅使用Django模板引擎而不是Jinja是值得的。

#7


2  

Thanks for the help folks. Here is one more addition. The case where you need to use custom template tags.

谢谢你们的帮助。这里还有一个加法。需要使用自定义模板标记的情况。

Let's say you have this important template tag in the module read.py

假设在模块read.py中有这个重要的模板标记

from django import template

register = template.Library()

@register.filter(name='bracewrap')
def bracewrap(value):
    return "{" + value + "}"

This is the html template file "temp.html":

这是html模板文件“temp.html”:

{{var|bracewrap}}

Finally, here is a Python script that will tie to all together

最后,这里有一个Python脚本,它将与所有脚本绑定在一起

import django
from django.conf import settings
from django.template import Template, Context
import os

#load your tags
from django.template.loader import get_template
django.template.base.add_to_builtins("read")

# You need to configure Django a bit
settings.configure(
    TEMPLATE_DIRS=(os.path.dirname(os.path.realpath(__file__)), ),
)

#or it could be in python
#t = Template('My name is {{ my_name }}.')
c = Context({'var': '*.com rox'})

template = get_template("temp.html")
# Prepare context ....
print template.render(c)

The output would be

的输出将是

{*.com rox}

#8


1  

Found this:

发现了这个:

http://snippets.dzone.com/posts/show/3339

http://snippets.dzone.com/posts/show/3339

#9


1  

Don't. Use StringTemplate instead--there is no reason to consider any other template engine once you know about it.

不喜欢。使用StringTemplate代替——一旦您知道了它,就没有理由再考虑任何其他模板引擎了。

#10


1  

An addition to what other wrote, if you want to use Django Template on Django > 1.7, you must give your settings.configure(...) call the TEMPLATES variable and call django.setup() like this :

另外,如果您想在Django > 1.7中使用Django模板,那么必须为您的settings.configure(…)调用模板变量并调用Django .setup()如下所示:

from django.conf import settings

settings.configure(TEMPLATES=[
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['.'], # if you want the templates from a file
        'APP_DIRS': False, # we have no apps
    },
])

import django
django.setup()

Then you can load your template like normally, from a string :

然后你可以像往常一样从字符串中加载模板:

from django import template   
t = template.Template('My name is {{ name }}.')   
c = template.Context({'name': 'Rob'})   
t.render(c)

And if you wrote the DIRS variable in the .configure, from the disk :

如果你在。configure中写入DIRS变量,从磁盘:

from django.template.loader import get_template
t = get_template('a.html')
t.render({'name': 5})

Django Error: No DjangoTemplates backend is configured

Django错误:没有配置DjangoTemplates后端

http://django.readthedocs.io/en/latest/releases/1.7.html#standalone-scripts

http://django.readthedocs.io/en/latest/releases/1.7.html standalone-scripts

#11


0  

I echo the above statements. Jinja 2 is a pretty good superset of Django templates for general use. I think they're working on making the Django templates a little less coupled to the settings.py, but Jinja should do well for you.

我同意上述声明。Jinja 2是一个非常好的Django模板的超集,可用于一般用途。我认为他们正在努力使Django模板与设置少一些耦合。是啊,但是金嘉应该做得很好。

#12


0  

While running the manage.py shell:

在运行管理。py壳:

>>> from django import template   
>>> t = template.Template('My name is {{ me }}.')   
>>> c = template.Context({'me': 'ShuJi'})   
>>> t.render(c)

#13


0  

Google AppEngine uses the Django templating engine, have you taken a look at how they do it? You could possibly just use that.

谷歌AppEngine使用Django模板引擎,您看过它们是如何实现的吗?你可以用这个。