python - Django 使用模板标签分割文本字段

标签 python html django python-3.x django-templates

我知道我可以使用 {{value|truncatewords:x}} 在给定字数后截断文本字段。如果我想在文本之间夹入一些内容,是否可以使用截断的部分后记?就像在 python 中使用字符串一样,如果我要给出

>>>string[:2]
>>>something in between
>>>string[2:]

但是使用模板标签,因为我正在迭代 for 循环并且无法将其传递到我的 View ?

谢谢

最佳答案

您需要一个custom template filter在这里。

这是一个基于 truncatewords() 的简单示例过滤器实现:

from django import template
from django.template.defaultfilters import stringfilter
from django.utils.text import Truncator

register = template.Library()

@register.filter(is_safe=True)
@stringfilter
def sandwich(value, args):
    length, cutlet = args.split(',')
    length = int(length)
    truncated_value = Truncator(value).words(length, truncate='')
    return ' '.join([truncated_value, cutlet, value[len(truncated_value):].strip()])

示例输出:

>>> from django.template import Template, Context
>>> template = Template('{% load filters %}{{ value|sandwich:"2,magic" }}')
>>> context = Context({'value': 'What a wonderful world!'})
>>> template.render(context)
u'What a magic wonderful world!'

请注意,Django 不允许在模板过滤器中传递多个参数 - 这就是为什么它们作为逗号分隔的字符串传递然后进行解析。在这里查看有关该想法的更多信息:How do I add multiple arguments to my custom template filter in a django template?

此外,您可能需要捕获可能的异常,以防字符串中仅传递一个参数、length 值无法转换为 int 等。

关于python - Django 使用模板标签分割文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24898662/

相关文章:

python - 使用Librosa Python向音频文件添加噪声并重新转换噪声信号

使用 Selenium 打开和关闭网站的 Python 类

html - 页脚元素的高度不断缩小

python - django-import-export ForeignKeyWidget 不进行查找

django - 跨表外键约束

python - Django - 什么是最佳实践 - 计算字段值

python - 如何访问FormView中的request对象

html - 溢出 : hidden on table causes bottom and right border to dissappear

php - 如何在点击链接时调用同一页面上的php文件

python - Django:如何从相关管理器访问原始实例?