Safe filter with django-haystack template label

I use Django Haystack to search on my site, but I need to filter out all the html code of my TextField with the "safe" template filter and select the search results according to the search criteria.

Is there any way to do this? I tried using

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

but that will not work.

+4
source share
5 answers

Remember to download the template tag {% highlight%}?

+1
source

Are you sure you want to highlight the words in your HTML document. This problem is complex (using a safe will not help you). Suppose your content is:

 <h1>my title</h1> my content 

If the custom content type is in the search box, you'll want to get something like this:

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

But wait a minute, what if the user enters h1 in the search. If you apply the algorithm naively, you will get:

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

So, to solve the problem, the marker should:

  • HTML parsing.
  • highlight in the analyzed document.
  • Print a document.

Unfortunately, I don’t know if anyone wrote such a large liner for a haystack. But you can write your own. This explains how: http://django-haystack.readthedocs.org/en/latest/highlighting.html

0
source

I also ran into this problem, and a workaround might be to use the with tag:

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

This works for me :)

0
source

This template tag will highlight words only for the text part of your html code.

 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) 
0
source

Source: https://habr.com/ru/post/1337602/


All Articles