Jinja2:渲染模板继承?
我想使用模板渲染融合的 Jinja2 和 Markdown 页面,如下所示:
{% block title %}{{ title }}{% endblock %}
# {{ title[0] }}
# {{ title[1] }}
## Introduction
我可以使用上面的代码来生成 HTML,但是当我将此脚本用于自定义创作应用程序时,我想能够为每种类型的条目定义主模板。
当我尝试通过扩展主模板 template.html
来呈现上述页面时:
{% extends 'template.html' %}
{% block title %}{{ title }}{% endblock %}
# {{ title[0] }}
# {{ title[1] }}
## Introduction
我收到错误:
Traceback (most recent call last):
File "compiler.py", line 55, in <module>
template = Template(text).render(parser.vars)
File "/usr/lib/python2.7/site-packages/jinja2/environment.py", line 891, in render
return self.environment.handle_exception(exc_info, True)
File "<template>", line 1, in top-level template code
TypeError: no loader for this environment specified
您可以看到有问题的行是 template = Template(text).render(解析器.vars)
。
有什么方法可以呈现上述模板代码并能够扩展 template.html
吗?
I'd like to render a fused Jinja2 and Markdown page using a template, which looks like so:
{% block title %}{{ title }}{% endblock %}
# {{ title[0] }}
# {{ title[1] }}
## Introduction
I can get that above code to generate HTML fine, but as I am using this script for a custom authoring application, I'd like to be able to define master templates for each type of entry.
When I try to render the above page by extending a master template, template.html
:
{% extends 'template.html' %}
{% block title %}{{ title }}{% endblock %}
# {{ title[0] }}
# {{ title[1] }}
## Introduction
I get an error:
Traceback (most recent call last):
File "compiler.py", line 55, in <module>
template = Template(text).render(parser.vars)
File "/usr/lib/python2.7/site-packages/jinja2/environment.py", line 891, in render
return self.environment.handle_exception(exc_info, True)
File "<template>", line 1, in top-level template code
TypeError: no loader for this environment specified
You can see that the problematic line is template = Template(text).render(parser.vars)
.
Is there any way that I can render the above template code and be able to extend template.html
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Jinja 的渲染器需要知道如何加载
template.html
,因此您需要为Environment
提供一个模板加载器实例。例如,假设文件
page.html
和template.html
位于当前目录中:更新 - 您可以创建自定义模板加载器,或使用 jinja2.loaders 中定义的现有类之一。例如,
DictLoader
会在dict()
实例中查找template.html
并将该值视为模板数据。从任何地方(例如 memcache、mysql、redis、Python 对象等)加载模板应该很简单。使用
DictLoader
的示例:page.html
Jinja's renderer needs to know how to load
template.html
, so you need to give theEnvironment
a template loader instance.For example, assuming the files
page.html
andtemplate.html
are in the current directory:Updated - You can create a custom template loader, or use one of the existing classes defined in jinja2.loaders. For example, the
DictLoader
would look uptemplate.html
in adict()
instance and treat the value as the template data. It should be straightforward to load your templates from just about anywhere (e.g. memcache, mysql, redis, a Python object, etc).Example of using
DictLoader
:page.html