Thu*_*orn 8 django django-templates django-filters
my_text = '''The template system works in a two-step process: compiling and rendering. A compiled template is, simply, a list of Node objects.
Thus, to define a custom template tag, you specify how the raw template tag is converted into a Node (the compilation function), and what the node’s render() method does.'''
Run Code Online (Sandbox Code Playgroud)
@register.filter(is_safe=True)
def format_description(description):
text = ''
for i in description.split('\n'):
text += ('<p class="site-description">' + i + '</p>')
return text
Run Code Online (Sandbox Code Playgroud)
我像这样得到原始 html 的输出
<p class="site-description">The template system works in a two-step process: compiling and rendering. A compiled template is, simply, a list of Node objects.</p><p class="site-description"> </p><p class="site-description"> Thus, to define a custom template tag, you specify how the raw template tag is converted into a Node (the compilation function), and what the node’s render() method does.</p>
Run Code Online (Sandbox Code Playgroud)
代替
模板系统分两步工作:编译和渲染。一个编译好的模板就是一个 Node 对象列表。
因此,要定义自定义模板标签,您需要指定原始模板标签如何转换为节点(编译函数),以及节点的 render() 方法做什么。
这个想法是获取文本并为拆分后创建的列表的每个部分创建不同的段落,以便文本可以格式化为漂亮和紧凑
nev*_*ner 16
要禁用自动转义,您可以使用mark_safe方法:
from django.utils.safestring import mark_safe
@register.filter(is_safe=True)
def format_description(description):
text = ''
for i in description.split('\n'):
text += ('<p class="site-description">' + i + '</p>')
return mark_safe(text)
Run Code Online (Sandbox Code Playgroud)
这在文档中明确涵盖:过滤器和自动转义。
您需要将输出标记为安全。
from django.utils.safestring import mark_safe
...
return mark_safe(text)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2428 次 |
| 最近记录: |