python - Django 模板标签

标签 python django

我正在寻找一个 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/

相关文章:

python - Django makemigrations 为未更改的模型字段创建新的迁移文件

Python Seaborn Distplot Y 值对应给定的 X 值

python - Jupyter Notebook 中的 Argparse 引发 TypeError

python - 覆盖python中的静态方法

python -/login/user login() 处的 TypeError 需要 1 个位置参数,但给出了 2 个

python - Django 限制文件下载

python - 如何避免在类里面使用 self.__dict__

python - datetime.date(2014, 4, 25) 在 Django 中不是 JSON 可序列化的

python - 同时使用组和个人权限

python - 使用两个模型进行全文搜索