【问题标题】:Using Django's templating engine without the rest of Django使用 Django 的模板引擎而不使用 Django 的其余部分
【发布时间】:2012-02-18 15:27:00
【问题描述】:

我正在构建一个应用程序,它使用 Django 模板引擎/语言来“编译”一些 HTML。但是,该应用程序不能在 Django 上运行,并且没有所有的配置和东西。 当我尝试使用它时,我收到以下错误:

Traceback (most recent call last):
  File "Send.py", line 33, in <module>
    template = loader.get_template("email.html")
  File "/Library/Python/2.7/site-packages/django/template/loader.py", line 157, in get_template
    template, origin = find_template(template_name)
  File "/Library/Python/2.7/site-packages/django/template/loader.py", line 138, in find_template
    raise TemplateDoesNotExist(name)
django.template.base.TemplateDoesNotExist: email.html

我使用的代码如下:

from django.template import loader, Context
from django.conf import settings

template = loader.get_template("email.html")
rendered = template.render(data)

模板与 Python 文件位于同一目录中。

【问题讨论】:

标签: python django templates


【解决方案1】:

我建议使用 Jinja2 而不是 Django 模板作为独立解决方案。

【讨论】:

  • 我同意这一点。如果您已经熟悉 Django 模板,您就会知道如何使用 Jinja2。它们几乎相同,但 Jinja 更好恕我直言。
  • Jinja2 python3 支持仍处于试验阶段
【解决方案2】:

你试过用这个吗?

settings.configure(TEMPLATE_DIRS=('.',))

由于模板与python代码在同一目录下,这应该足以让加载器找到模板。

【讨论】:

    【解决方案3】:

    为了让加载器找到你的模板;您需要在settings.py 中的TEMPLATE_DIRS 元组中拥有模板所在的目录。默认情况下,django 将搜索templates 目录在应用程序中,所以如果您没有注册应用程序; django 找不到模板。

    如果您使用“django like”模板引擎,jinja 非常接近 django 的语法并且完全独立,您不会遇到现在所面临的意外问题。

    【讨论】:

      猜你喜欢
      • 2016-03-06
      • 2010-09-11
      • 1970-01-01
      • 2023-03-25
      • 2018-05-04
      • 2016-08-23
      • 1970-01-01
      • 1970-01-01
      • 2013-01-26
      相关资源
      最近更新 更多