-2

我正在使用safe过滤器,我只想转义到标签中的 HTML 标签<code></code>,这意味着<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('<', '&lt;')
    string = string.replace('>', '&gt;')
    string = string.replace("'", '&#39')
    string = string.replace('"', '&quot')
    final_string = string.replace('&', '&amp')
    return final_string

模板.html

.......

{% load sanitizer %}
{% load custom_filters %}

......

{{ content|escape_html|safe|linebreaks|code_escape }}

.......
4

1 回答 1

0

find_all returns a ResultSet which is iterable. I believe you can then edit the .string value of the tag. Try something like this:

soup = BeautifulSoup(value)
for code_tag in soup.find_all('code'):
    code_tag.string = code_tag.string.replace('<', '&lt;')
    code_tag.string = code_tag.string.replace('>', '&gt;')
    code_tag.string = code_tag.string.replace("'", '&#39')
    code_tag.string = code_tag.string.replace('"', '&quot')
    code_tag.string = code_tag.string.replace('&', '&amp')
return str(soup)
于 2013-10-21T12:51:53.887 回答