是否有处理“…更多”的Django模板过滤器,当您单击它时,它会显示更多文本?

发布于 2021-01-29 16:03:36

假设我有一段很长的段落。

我只希望显示前15个字。之后,该人单击“更多”以查看其余内容。

关注者
0
被浏览
48
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    只是简单地说明了这一点,似乎可以完成您想做的事,并且不依赖任何外部JS库。

    免责声明:我没有在IE中尝试过,但是chrome和firefox可以正常工作。

    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, '">read 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
    

    要使用它,只需在您的应用中创建一个templatetags文件夹,在其中创建__init__.py文件,然后将此代码放入即可readmore.py

    然后在要使用它的任何模板的顶部,只需添加: {% load readmore %}

    要使用过滤器本身:

    {{ some_long_text_var|readmore:15 }}

    :15告诉您在阅读更多链接之前要显示多少个单词。

    如果您想像Ajax一样加载全部内容,那会有些不同,并且需要更多的基础架构。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看