将模板中的特定块呈现为字符串。
django-render-block的Python项目详细描述
django渲染块
从django模板呈现特定块标记的内容。为…工作 任意模板继承,即使在子模板中定义了块 但不是在父母身上。一般来说,它的工作方式类似于来自django的render_to_string, 但允许您指定要渲染的块。
功能
- 从模板渲染特定块
- 完全支持Django模板引擎
- 部分支持Jinja2引擎:它支持 当前未处理extends标记。
要求
django渲染块支持django 1.11、2.1和2.2。
示例
在test1.html:
{%blockblock1%}block1 from test1{%endblock%}{%blockblock2%}block2 from test1{%endblock%}
在test2.html:
{%extends'test1.html'%}{%blockblock1%}block1 from test2{%endblock%}
从python外壳:
>>>fromrender_blockimportrender_block_to_string>>>printrender_block_to_string('test2.html','block1')u'block1 from test2'>>>printrender_block_to_string('test2.html','block2')u'block2 from test1'
它还可以接受一个上下文作为dict(就像render_to_string),在 test3.html:
{%blockblock3%}Render this {{variable}}!{%endblock%}
来自python:
>>>printrender_block_to_string('test3.html','block3',{'variable':'test'})u'Render this test!'
API参考
api很简单,它试图镜像内置的render_to_stringapi。
render_block_to_string(template_name, block_name, context=None, request=None)
- ^{tt10}$
- The name of the template to load and render. If it’s a list of template names, Django uses ^{tt11}$ instead of ^{tt12}$ to find the template.
- ^{tt13}$
- The name of the block to render from the above template.
- ^{tt14}$
A ^{tt5}$ to be used as the template’s context for rendering.
^{tt14}$ is now optional. An empty context will be used if it isn’t provided.
- ^{tt17}$
The request object used to render the template.
^{tt17}$ is optional and works only for Django templates. If provided a ^{tt19}$ will be used instead of a ^{tt20}$.
例外情况
类似于render_to_string,这将引发以下异常:
- ^{tt22}$
- Raised if the template(s) specified by ^{tt10}$ cannot be loaded.
- ^{tt24}$
- Raised if the loaded template contains invalid syntax.
还有两个额外的错误可以引起:
- ^{tt25}$
- Raised if the block given by ^{tt13}$ does not exist in the template.
- ^{tt27}$
- Raised if a template backend besides the Django backend is used.
贡献
如果你发现了一个bug或者对django渲染块有了改进的想法, 拜托 file an issue或 提供拉取请求!检查 list of issues用于 关于该做什么的想法。
归因
这是基于以下几个来源:
- 最初Django Snippet 769
- 更新版本Django Snippet 942
- 片段的一个版本被移植为Django-Block-Render
- 另一个灵感来自django-templated-email
- 也基于a StackOverflow answer 2687173
更改日志
0.6(2019年5月8日)
- 支持django 1.11、django 2.1和django 2.2。
- 支持Python2.7、3.5、3.6和3.7。
- render_block_to_string现在可以选择接受一个request参数。 如果给定一个RequestContext而不是Context,则当 使用django模板引擎进行渲染。看15,多亏了“复古”。
0.5(2016年9月1日)
- 修复了继承模板和呈现在 父模板,但覆盖子模板中的一部分。 (#8)
0.3.1(2016年6月1日)
- 重构以使其更通用(可能支持多个 模板引擎)。
0.3(2016年5月27日)
- 大部分是重写的。
- 更新以支持现代django(1.8,1.9):
- 防止不同的模板后端。
- 为每个节点使用内部api。
- 已删除context_instance参数。
- 支持调用{{ block.super }}。
0.2.2(2011年1月10日)
- 根据更新 comment 3466 on Django Snippet 942 修复嵌套扩展的问题。特定的错误是不可复制的, 但是附加的代码应该不会有什么影响。
0.2.1(2010年8月27日)
- 根据更新 comment 3237 on Django Snippet 942 移除无意义的渲染。特定的错误是不可复制的,但是 代码是无关的。
0.2(2008年8月4日)
- 更新版本自 Django Snippet 942作者:zbyte64。
- 改进包括:
- 更简单/更好地处理“extends”块标记
- 搜索if/else块
- 更少的代码
- 允许传递模板列表,该列表更接近 将“u”呈现为“u”响应
0.1(2008年5月22日)
- 初始版本来自 Django Snippet 769由sciyosh提供i.
- 支持django 0.96。