您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

只是简单地说明了这一点,似乎可以完成您想做的事,并且不依赖任何外部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一样加载全部内容,那会有些不同,并且需要更多的基础架构。

Go 2022/1/1 18:52:49 有491人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶