Split by a word (case insensitive)

后端 未结 3 1480
一向
一向 2020-12-11 15:34

If I want to take

\"hi, my name is foo bar\"

and split it on \"foo\", and have that split be case insensitive (split on any of

3条回答
  •  轮回少年
    2020-12-11 16:31

    This is not the exact answer but the solution based on the question. After searching awhile on the net I implemented the following.

    This is my custom tag (see how to do it).

    from django.template.defaultfilters import register
    from django.utils.html import escape
    from django.utils.safestring import mark_safe
    
    @register.simple_tag
    def highlight(string, entry, prefix, suffix):
        string = escape(string)
        entry = escape(entry)
        string_upper = string.upper()
        entry_upper = entry.upper()
        result = ''
        length = len(entry)
        start = 0
        pos = string_upper.find(entry_upper, start)
        while pos >= 0:
            result += string[start:pos]
            start = pos + length
            result += prefix + string[pos:start] + suffix
            pos = string_upper.find(entry_upper, start)
        result += string[start:len(string)]
        return mark_safe(result)
    

    It accepts unsafe string and returns the escaped result.

    Use it this way:

    {% highlight entity.code search_text '' '' %}
    

    I use a nested to inherit all the style. And it shows something like

提交回复
热议问题