Python Django-Teplatetag“;阅读更多“;“想成为”;“无读”;

Python Django-Teplatetag“;阅读更多“;“想成为”;“无读”;,python,django,templatetag,Python,Django,Templatetag,不久前我写了一个模板标签,它的功能是在15个单词后折叠一个文本块。现在我想要完全相反的东西。我希望用户能够回到原来的15字折叠文本打开后,折叠文本块 我知道听起来有点紧张 readmore.py from django import template from django.utils.html import escape from django.utils.safestring import mark_safe register = template.Library() import re

不久前我写了一个模板标签,它的功能是在15个单词后折叠一个文本块。现在我想要完全相反的东西。我希望用户能够回到原来的15字折叠文本打开后,折叠文本块

我知道听起来有点紧张

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
来自django导入模板的

从django.utils.html导入转义
从django.utils.safestring导入标记_safe
register=template.Library()
进口稀土
readmore\u showscript=''。加入([
“this.parentNode.style.display='none';”,
“this.parentNode.parentNode.getElementsByClassName('more')[0].style.display='inline';”,
“返回false;”,
]);
@寄存器过滤器
def readmore(txt,showwords=15):
全局readmore\u showscript
words=re.split(r'',转义(txt))

如果您知道len(words),您可以使用
template\u标记
来呈现html模板。。。这几乎肯定比在python中处理html更容易。。。也就是说,这不管用吗?当您单击链接以显示更多内容时,javascript控制台中是否存在错误?ie什么不起作用?你上面看到的代码是一个模板标签…根本没有错误。我只是想知道如何将文本折叠回来。。。正如名字所说,readmore.py模板标记显示更多内容。我想知道我怎样才能回到由上面的脚本制作的原始缩短文本。啊,我明白了。。。好的,与其设置
display:inline
,不如设置
display:none
。。。您可能有责任将其放入javascript中的一个函数中,该函数用于“切换”显示(即如果显示隐藏它…如果隐藏显示它),这就是重点。不知道JS。希望有人能帮我。。。