template tag inside object TextField

喜欢而已 提交于 2019-12-20 06:28:25

问题


I need custom template tag inside model.TextField value. Value from the object text field have something like "lorem ipsum dolor {% mytag %}" but "mytag" is not rendered as template tag. It is registered in the library as tag and loaded on the page and I have {{ object.textfield|safe }} filter. Is it possible at all?


回答1:


As Django's template engine can easily be used anywhere in your code you should be able to do something like this:

from django.template import Context, Template
rendered = Template("{% load your_tag_library %}",
    object.textfield).render(Context())

Rather than rendering the template from a file it renders it from a string like:

"{% load your_tag_library %}lorem ipsum dolor {% mytag %}"

The code can for instance be used in your view or as a method on your model. Note that the Context is empty, you might as well pass a dict with template variables to it.

Furthermore, to handle it directly in the template you could write a custom templatetag which does something similiar, basically a templatetag that parses strings for templatetags.



来源:https://stackoverflow.com/questions/11874325/template-tag-inside-object-textfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!