django 模板标签缩短字符串

django template tag shorten string

我在模板中有以下内容 -

<tes:productiondate>{% now "Y-m-d" %}T{% now "H:i:s" %}-{{{% now "u" %}|truncatechars:4}}</tes:productiondate>

它给我一个错误

Could not parse some characters: |{% now "u" %}||truncatechars:4

{% now "u" %} 确实显示正确问题是默认情况下它显示 6 个字符,而我只希望它显示 4 个字符。

我意识到 truncatechars 是正确的方法,因为我不想要“...”那么我该如何将 6 个字符的字符串缩短为只有 4 个?

您不能对模板标签的输出应用过滤器。在 django 的主干版本中 {% now %} 标记可以将格式化时间保存到变量:

{% now "u" as msec %}{{ msec|truncatechars:4 }}

但是在当前稳定的django (1.7.2)中不支持as关键字。

所以你要写custom template tag。很简单:

import datetime
from django import template

register = template.Library()

@register.simple_tag
def microseconds(format_string):
    return datetime.datetime.now().strftime('%f')[:4]