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