【问题标题】:Django splitting a textfield using template tagsDjango 使用模板标签拆分文本字段
【发布时间】:2014-09-13 22:33:04
【问题描述】:

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

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

但是使用模板标签是因为我正在迭代一个 for 循环并且无法通过我的视图传递它?

谢谢

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2017-04-23
      • 2013-07-30
      • 2016-03-24
      • 2018-11-11
      • 2011-07-11
      • 2014-03-20
      • 1970-01-01
      • 2011-06-15
      • 1970-01-01
      相关资源
      最近更新 更多