安全过滤器与高亮模板标签django-haystack

时间:2011-01-29 17:29:32

标签: python django django-templates django-haystack

我正在使用Django Haystack在我的网站上进行搜索,但我需要使用模板过滤器"safe"过滤我的TextField的所有html代码,并根据搜索条件突出显示搜索结果。

有办法做到这一点吗?我试过

{% highlight result.object.content|safe with query %}

但它不起作用。

5 个答案:

答案 0 :(得分:1)

你不要忘记加载{%highlight%}模板标签吗?

答案 1 :(得分:0)

您真正想要的是突出显示HTML文档中的单词。这个问题很难(使用安全无助于你)。假设您的内容是:

<h1>my title</h1>
my content

如果用户在搜索框中输入content,您将需要获得以下内容:

<h1>my title</h1>
my <em>content</em>

但是等一下,如果用户在搜索中输入h1怎么办?如果你天真地应用算法,你会得到:

<<em>h1</em>>my title</<em>h1</em>>
my content

所以要解决问题,荧光笔应该:

  1. 解析HTML。
  2. 在已解析的文档中突出显示。
  3. 打印文档。
  4. 不幸的是,我不知道是否有人为干草堆写了这么高的报纸。但你可以自己写。以下是如何解释:http://django-haystack.readthedocs.org/en/latest/highlighting.html

答案 2 :(得分:0)

我也遇到过这个问题,解决方法可能是使用with标记:

{% load highlight %}
{% with obj.text|safe as text %}
    {% highlight text with my_query %}
{% endwith %}

这对我有用:)

答案 3 :(得分:0)

此模板标记仅突出显示html代码文本部分的单词。

import re

from django import template
from django.utils.safestring import mark_safe

register = template.Library()


@register.tag(name="highlight")
def do_highlight(parser, token):
    tag_name, words = token.contents.split(' ', 1)
    nodelist = parser.parse(('endhighlight',))
    parser.delete_first_token()
    return HighlightNode(nodelist, words)

class HighlightNode(template.Node):
    def __init__(self, nodelist, words):
        self.nodelist = nodelist
        self.words = words

    def render(self, context):
        # initial data
        html_data = self.nodelist.render(context)

        # prepare words to be highlighted
        words = context.get(self.words, "")
        if words:
            words = [w for w in re.split('[^\w]+', words) if w]
            pattern = re.compile(r"(?P<filter>%s)" % '|'.join(words), re.IGNORECASE)
        else :
            # no need to go further if there is nothing to highlight
            return html_data

        # parse the html
        chunks = html_data.split('<')
        parsed_data = [chunks.pop(0)]

        # separate tag and text
        for chunk in chunks:
            if chunk:
                if '>' in chunk:
                    tagdata, text = chunk.split('>', 1)
                    endtag = '>'
                else:
                    # the tag didn't end
                    tagdata, text, endtag = chunk, '', ''

                # rebuild tag
                parsed_data.append('<')
                parsed_data.append(tagdata)
                parsed_data.append(endtag)

                # highligh words in text
                if text:
                    text = mark_safe(re.sub(pattern,
                                            r'<span class="highlight">\g<filter></span>',
                                            text))
                    parsed_data.append(text)

        return ''.join(parsed_data)

答案 4 :(得分:-1)

相关问题