我正在寻找一个 django 模板标签,它可以计算单词数并对整个段落进行子字符串化,而无需截断单词。有内置函数吗?我尝试查看 Django 模板文档中的内置函数列表,但找不到任何内容。
请指教?
最佳答案
这是我的实现。它实际上是砍下一个句子而不是一个段落,但无论如何你应该有一个想法。
{% splitarticle some_data word_count %}
{{ pre_part }}
{% if post_part %}
{{ post_part }}
{% endif %}
它将返回两个变量
还有代码。您应该放入 < your_app >/templatetags/
from django import template
from django.utils.encoding import force_unicode
def split_by_sentence(text, word_count):
words = force_unicode(text).strip().split(' ')
word_count = int(word_count)
if len(words)>word_count:
cnt = word_count
for word in words[word_count:]:
cnt+=1
if '.' in word or '?' in word or '!' in word:
break
if cnt>=len(words):
cnt = word_count
pre = ' '.join(words[:cnt])
post = ' '.join(words[cnt:])
return pre, post
else:
return text, None
register = template.Library()
@register.tag
def splitarticle(parser, token):
try:
tag, data, word_count = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError('splitarticle parsing error')
return SplitArticleNode(data, word_count)
class SplitArticleNode(template.Node):
def __init__(self, data, word_count):
self.data = template.Variable(data)
self.word_count = word_count
def render(self, context):
data = self.data.resolve(context)
context['pre_part'], context['post_part'] = split_by_sentence(data, self.word_count)
return ''
关于python - Django 模板标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4707008/