我知道我可以使用 {{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/