Django - Teplatetag “readmore” wants to be “readless”

醉酒当歌 提交于 2020-01-06 04:35:28


i have written a template tag some time ago which has the feature to collapse a textblock after 15 words. Now i want the exact opposite thing. i want that the user is able to get back to the original 15 words collapsed text after opening the collapsed textblock...

i know sounds a bit wired.

from django import template
from django.utils.html import escape
from django.utils.safestring import mark_safe

register = template.Library()

import re

readmore_showscript = ''.join([
"return false;",


def readmore(txt, showwords=15):
    global readmore_showscript
    words = re.split(r' ', escape(txt))

    if len(words) <= showwords:
        return txt

    # wrap the more part
    words.insert(showwords, '<span class="more" style="display:none;">')

    # insert the readmore part
    words.insert(showwords, '<span class="readmore">... <a href="#" onclick="')
    words.insert(showwords+1, readmore_showscript)
    words.insert(showwords+2, '">more</a>')
    words.insert(showwords+3, '</span>')

    # Wrap with <p>
    words.insert(0, '<p>')

    return mark_safe(' '.join(words))

readmore.is_safe = True