问题:在没有其他Django的情况下如何使用Django模板?
我想在我的(Python)代码中使用Django模板引擎,但是我没有构建基于Django的网站。如何在没有settings.py文件(和其他文件)且没有设置DJANGO_SETTINGS_MODULE环境变量的情况下使用它?
如果我运行以下代码:
>>> import django.template
>>> from django.template import Template, Context
>>> t = Template('My name is {{ my_name }}.')
我得到:
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
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?
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.
回答 0
解决方案很简单。它实际上有据可查,但不太容易找到。(我必须仔细研究-当我尝试了几种其他的Google搜索时并没有出现。)
以下代码有效:
>>> 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.'
有关您可能要定义的某些设置(作为要配置的关键字参数)的说明,请参阅Django文档(上文链接)。
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).
回答 1
Jinja2 语法与Django几乎相同,只是差别很小,而且您获得了功能更强大的模板引擎,该引擎还将模板编译为字节码(FAST!)。
我使用它来进行模板化,包括在Django本身中,它非常好。如果缺少某些所需功能,您也可以轻松编写扩展名。
这是代码生成的一些演示:
>>> 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'
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!).
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.
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'
回答 2
您要使用Django模板的任何特殊原因?无论神社和元史是,在我看来,优越。
如果您确实愿意,请参见中的。特别是“使用设置而不设置DJANGO_SETTINGS_MODULE
”部分。使用这样的东西:
from django.conf import settings
settings.configure (FOO='bar') # Your settings go here
Any particular reason you want to use Django’s templates? Both Jinja and Genshi are, in my opinion, superior.
If you really want to, then see the . Especially the section “Using settings without setting DJANGO_SETTINGS_MODULE
“. Use something like this:
from django.conf import settings
settings.configure (FOO='bar') # Your settings go here
回答 3
我还建议jinja2。关于vs. 有一篇不错的文章,其中提供了一些详细信息,说明您为什么偏爱后者。django
jinja2
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.
回答 4
根据Jinja文档,Python 3支持仍处于试验阶段。因此,如果您使用的是Python 3,而性能不是问题,则可以使用django的内置模板引擎。
Django 1.8引入了对多个模板引擎的支持,这需要更改模板的初始化方式。您必须显式配置settings.DEBUG
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"
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.
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.
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"
回答 5
除了其他人写的东西之外,如果要在Django> 1.7上使用Django模板,则必须给您的settings.configure(…)调用TEMPLATES变量,然后像这样调用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()
然后,您可以像通常一样从字符串加载模板:
from django import template
t = template.Template('My name is {{ name }}.')
c = template.Context({'name': 'Rob'})
t.render(c)
而且,如果您在磁盘中的.configure中写入了DIRS变量,则:
from django.template.loader import get_template
t = get_template('a.html')
t.render({'name': 5})
Django错误:未配置DjangoTemplates后端
http://django.readthedocs.io/zh-CN/latest/releases/1.7.html#standalone-scripts
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 :
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 :
from django.template.loader import get_template
t = get_template('a.html')
t.render({'name': 5})
Django Error: No DjangoTemplates backend is configured
http://django.readthedocs.io/en/latest/releases/1.7.html#standalone-scripts
回答 6
我也会说Jinja。它绝对比Django Templating Engine 更强大,并且是独立的。
如果这是现有Django应用程序的外部插件,则可以创建一个自定义命令,并在项目环境中使用模板引擎。像这样;
manage.py generatereports --format=html
但是我认为仅仅使用Django模板引擎而不是Jinja是不值得的。
I would say Jinja as well. It is definitely more powerful than Django Templating Engine and it is stand alone.
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;
manage.py generatereports --format=html
But I don’t think it is worth just using the Django Templating Engine instead of Jinja.
回答 7
谢谢大家的帮助。这是另外一个。您需要使用自定义模板标签的情况。
假设您在read.py模块中有这个重要的模板标签
from django import template
register = template.Library()
@register.filter(name='bracewrap')
def bracewrap(value):
return "{" + value + "}"
这是html模板文件“ temp.html”:
{{var|bracewrap}}
最后,这是一个将所有内容捆绑在一起的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': 'stackoverflow.com rox'})
template = get_template("temp.html")
# Prepare context ....
print template.render(c)
输出将是
{stackoverflow.com rox}
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
from django import template
register = template.Library()
@register.filter(name='bracewrap')
def bracewrap(value):
return "{" + value + "}"
This is the html template file “temp.html”:
{{var|bracewrap}}
Finally, here is a Python script that will tie to all together
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': 'stackoverflow.com rox'})
template = get_template("temp.html")
# Prepare context ....
print template.render(c)
The output would be
{stackoverflow.com rox}
回答 8
回答 9
Don’t. Use StringTemplate instead–there is no reason to consider any other template engine once you know about it.
回答 10
我回应以上陈述。Jinja 2是通用模板的一个很好的Django模板超集。我认为他们正在努力使Django模板与settings.py的耦合度降低一些,但是Jinja应该为您做的更好。
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.
回答 11
运行manage.py
外壳程序时:
>>> from django import template
>>> t = template.Template('My name is {{ me }}.')
>>> c = template.Context({'me': 'ShuJi'})
>>> t.render(c)
While running the manage.py
shell:
>>> from django import template
>>> t = template.Template('My name is {{ me }}.')
>>> c = template.Context({'me': 'ShuJi'})
>>> t.render(c)
回答 12
Google AppEngine
使用Django模板引擎,您是否看过它们的工作方式?您可以使用它。
Google AppEngine
uses the Django templating engine, have you taken a look at how they do it? You could possibly just use that.
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。