有没有处理“...更多”的Django模板过滤器?点击后显示更多文本?
假设我有一大段文字。
我只想显示前15个单词。之后,用户可以点击“更多”来查看剩下的内容。
5 个回答
0
有一个叫做 truncatewords 的过滤器,虽然你还是需要一个JavaScript的辅助工具来完成你所说的事情。
2
使用 truncatechars_html
参考链接: https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#truncatechars-html
truncatechars_html
Similar to truncatechars, except that it is aware of HTML tags. Any tags that are opened in the string and not closed before the truncation point are closed immediately after the truncation.
For example:
{{ value|truncatechars_html:9 }}
If value is "<p>Joel is a slug</p>", the output will be "<p>Joel i...</p>".
Newlines in the HTML content will be preserved.
5
我刚刚做了这个,似乎可以满足你的需求,而且不需要依赖任何外部的JavaScript库。
注意:我还没在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加载完整内容,那就需要做一些不同的设置,工作量会大一些。