对象TextField内的模板标签 [英] template tag inside object TextField

查看:82
本文介绍了对象TextField内的模板标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 model.TextField 中的自定义模板标签。来自对象文本字段的值具有类似于lorem ipsum dolor {%mytag%}但mytag未被渲染为模板标记。它在库中作为标签注册并加载到页面上,我有 {{object.textfield | safe}} 过滤器。这是可能的吗?

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?

推荐答案

由于Django的模板引擎可以轻松地在代码中的任何地方使用,您应该可以做某事像这样:

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 %}"

代码可以例如在您的视图中使用或作为模型上的方法使用。请注意,上下文是空的,您也可以通过一个带有模板变量的dict。

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.

这篇关于对象TextField内的模板标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆