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

查看:14
本文介绍了对象 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 %}"

例如,代码可以在您的视图中使用或作为模型上的方法使用.请注意,Context 为空,您不妨将带有模板变量的 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天全站免登陆