我正在使用safe
过滤器,我想要转义为<code></code>
标记中的HTML标记,这意味着<b>Hello</b>
将呈现为 Hello 但<code><b>Hello</b></code>
将呈现为<b>Hello</b>
。所以我写自定义过滤器,但我得到这个错误:
Exception Type: AttributeError
Exception Value:'ResultSet' object has no attribute 'replace'
Exception Location: G:\python\Python\python practice\python website\firstpage\custom_filters\templatetags\custom_filters.py in code_escape, line 10
我的代码是:
from bs4 import BeautifulSoup
from django import template
register = template.Library()
@register.filter
def code_escape(value):
soup = BeautifulSoup(value)
response = soup.find_all('code')
string = response.replace('<', '<')
string = string.replace('>', '>')
string = string.replace("'", ''')
string = string.replace('"', '"')
final_string = string.replace('&', '&')
return final_string
template.html
.......
{% load sanitizer %}
{% load custom_filters %}
......
{{ content|escape_html|safe|linebreaks|code_escape }}
.......
答案 0 :(得分:0)
find_all
返回可迭代的ResultSet
。我相信您可以编辑代码的.string
值。尝试这样的事情:
soup = BeautifulSoup(value)
for code_tag in soup.find_all('code'):
code_tag.string = code_tag.string.replace('<', '<')
code_tag.string = code_tag.string.replace('>', '>')
code_tag.string = code_tag.string.replace("'", ''')
code_tag.string = code_tag.string.replace('"', '"')
code_tag.string = code_tag.string.replace('&', '&')
return str(soup)