django动态包含标签

戈兰

我正在尝试向模板中添加一些图片库,但是该图片库在页面上的位置需要由用户定义。有时它将在文本的顶部,有时在页面的文本的结尾,有时在页面的中间。在文本字段中,用户将添加此行,#foto并根据该行的位置来渲染图库。例如:

some paragraph written by user in the text field...

#foto

some another paragraph written by user ...

现在,最简单的方法是#foto在视图中替换为include标签。如:

foto = "{% include 'includes/gallery.html' %}"
xx = "#foto"
post.text = post.text.replace(xx, foto)

但是此示例不起作用,因为不能以这种方式调用include标记。它以纯文本{%include'includes / gallery.html'%}的形式呈现。可以执行的渲染包括#foto文本位置上预期的标记

欺骗

在视图内分配foto渲染的模板:

...
from django.template.loader import render_to_string
"""
Get the items from the model, define your query
"""
gallery = GalleryModel.objects.all()
"""
Render gallery template and assign to foto, which then you
can inject in the basic template
"""
foto = render_to_string('includes/gallery.html', {'gallery': gallery})
...

然后在您的模板中:

{{ foto }}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章