是否有处理“...more"的 Django 模板过滤器?当你点击它时,它会显示更多的文字? [英] Is there a Django template filter that handles "...more" and when you click on it, it shows more of the text?

查看:12
本文介绍了是否有处理“...more"的 Django 模板过滤器?当你点击它时,它会显示更多的文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个很大的段落.

Suppose I have a huge paragraph.

我只想显示前 15 个单词.之后,此人点击更多"以查看其余内容.

I just want the top 15 words to be shown. After than, the person clicks "more" to see the rest of the stuff.

推荐答案

刚刚做了这个,似乎可以做你想做的,并且不依赖任何外部 JS 库.

Just whipped this up, seems to do what you want, and there's no dependency on any external JS libs.

免责声明:我没有在 IE 中尝试过这个,但 chrome 和 firefox 工作正常.

DISCLAIMER: I haven't tried this in IE, but chrome and firefox work fine.

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.

To use it, just create a templatetags folder in your app, create the __init__.py file in there, and then drop this code into readmore.py.

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

Then at the top of any template where you want to use it, just add: {% load readmore %}

使用过滤器本身:

{{ some_long_text_var|readmore:15 }}

:15 告诉您要在阅读更多链接之前显示多少个字.

The :15 tells how many words you want to show before the read more link.

如果您想要像 ajax 加载完整内容这样的花哨的东西,那就有点不同了,需要更多的基础设施.

If you want anything fancy like ajax loading of the full content, that's quite a bit different and would require a bit more infrastructure.

这篇关于是否有处理“...more"的 Django 模板过滤器?当你点击它时,它会显示更多的文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆