14

有没有办法让 django-haystack 的{% highlight %}模板标签显示传入的完整变量,而不是在第一次匹配之前删除所有内容?

我这样使用它:

{% highlight thread.title with request.GET.q %}
4

2 回答 2

10

我从未使用过 haystack,但从文档源代码中快速查看,您可以制作自己的自定义荧光笔并告诉 haystack 使用它

from haystack.utils import Highlighter
from django.utils.html import strip_tags

class MyHighlighter(Highlighter):
    def highlight(self, text_block):
        self.text_block = strip_tags(text_block)
        highlight_locations = self.find_highlightable_words()
        start_offset, end_offset = self.find_window(highlight_locations)

        # this is my only edit here, but you'll have to experiment
        start_offset = 0
        return self.render_html(highlight_locations, start_offset, end_offset)

然后设置

HAYSTACK_CUSTOM_HIGHLIGHTER = 'path.to.your.highligher.MyHighlighter'

在你的 settings.py

于 2011-10-29T11:21:19.317 回答
2

@second 的答案有效,但是,如果您也不希望它切断字符串的结尾并且您的长度低于最大长度,您可以试试这个。仍在测试它,但它似乎工作:

class MyHighlighter(Highlighter):
    """
    Custom highlighter
    """
    def highlight(self, text_block):
        self.text_block = strip_tags(text_block)
        highlight_locations = self.find_highlightable_words()
        start_offset, end_offset = self.find_window(highlight_locations)
        text_len = len(self.text_block)

        if text_len <= self.max_length:
            start_offset = 0
        elif (text_len - 1 - start_offset) <= self.max_length:
            end_offset = text_len
            start_offset = end_offset - self.max_length

        if start_offset < 0:
            start_offset = 0
        return self.render_html(highlight_locations, start_offset, end_offset)
于 2014-05-08T21:14:52.560 回答