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.

readmore.py

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([
"this.parentNode.style.display='none';",
"this.parentNode.parentNode.getElementsByClassName('more')[0].style.display='inline';",
"return false;",

]);

@register.filter
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;">')
    words.append('</span>')

    # 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>')
    words.append('</p>')

    return mark_safe(' '.join(words))

readmore.is_safe = True

来源:https://stackoverflow.com/questions/51250759/django-teplatetag-readmore-wants-to-be-readless

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!