search highlights

This commit is contained in:
Their Name 2022-01-02 09:13:32 -05:00 committed by Your Name
parent b4cc28f4a6
commit c7028d6e87
5 changed files with 23 additions and 12 deletions

View file

@ -153,11 +153,15 @@ class Indexer:
# print(r)
import types
results = types.SimpleNamespace()
results.items = list(map(lambda i: self.item_to_obj(i), r['hits']))
results.items = list([x for x in map(lambda i: self.item_to_obj(i), r['hits']) if x is not None])
results.num_pages = (r['nbHits'] + SEARCH_PAGE_SIZE - 1) // SEARCH_PAGE_SIZE
# print(results)
return results
@classmethod
def item_to_obj(self, item):
return self.class_map[item['_class']].objects.get(id=item['id'])
try:
return self.class_map[item['_class']].objects.get(id=item['id'])
except Exception as e:
logger.error(f"unable to load search result item from db:\n{item}")
return None

View file

@ -43,9 +43,7 @@
<ul class="entity-list__entities">
{% for item in items %}
{% include "partial/list_item.html" %}
{% empty %}
<li class="entity-list__entity">
{% trans '无站内条目匹配' %}

View file

@ -66,16 +66,12 @@
{% if movie.director %}{% trans '导演' %}:
{% for director in movie.director %}
<<<<<<< Updated upstream
{{ director }}{% if not forloop.last %} {% endif %}
=======
{% if request.GET.q %}
{{ director | highlight:request.GET.q }}
{% else %}
{{ director }}
{% endif %}
{% if not forloop.last %},{% endif %}
>>>>>>> Stashed changes
{% endfor %}/
{% endif %}
@ -89,7 +85,13 @@
<span class="entity-list__entity-info entity-list__entity-info--full-length">
{% if movie.actor %}{% trans '主演' %}:
{% for actor in movie.actor %}
<span {% if forloop.counter > 5 %}style="display: none;" {% endif %}>{{ actor }}</span>
<span {% if forloop.counter > 5 %}style="display: none;" {% endif %}>
{% if request.GET.q %}
{{ actor | highlight:request.GET.q }}
{% else %}
{{ actor }}
{% endif %}
</span>
{% if forloop.counter <= 5 %}
{% if not forloop.counter == 5 and not forloop.last %} {% endif %}
{% endif %}

View file

@ -1,13 +1,19 @@
from django import template
from django.utils.safestring import mark_safe
from django.template.defaultfilters import stringfilter
from django.utils.html import format_html
from opencc import OpenCC
import re
cc = OpenCC('t2s')
register = template.Library()
@register.filter
@stringfilter
def highlight(text, search):
return mark_safe(text.replace(search, f'<span class="highlight">{search}</span>')) # TODO better query words match
for s in cc.convert(search.strip().lower()).split(' '):
if s:
p = cc.convert(text.lower()).find(s)
if p != -1:
text = f'{text[0:p]}<span class="highlight">{text[p:p+len(s)]}</span>{text[p+len(s):]}'
return mark_safe(text)

View file

@ -14,3 +14,4 @@ requests
filetype
setproctitle
tqdm
opencc