簡體   English   中英

安全過濾器與高亮模板標簽django-haystack

[英]Safe filter with highlight template tag django-haystack

我正在使用Django Haystack在我的網站上進行搜索,但我需要使用模板過濾器“safe”過濾我的TextField的所有html代碼,並根據搜索條件突出顯示搜索結果。

有沒有辦法做到這一點? 我試過了

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

但它不起作用。

你不要忘記加載{%highlight%}模板標簽嗎?

你真正想要的是突出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. 打印文件。

不幸的是,我不知道是否有人為干草堆寫了這么高的人。 但你可以自己寫。 這里解釋如何: http//django-haystack.readthedocs.org/en/latest/highlighting.html

我也遇到過這個問題,解決方法可能是使用with標簽:

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

這對我有用:)

此模板標記僅突出顯示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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM