您需要在这里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 等。