django模板标签缩短字符串

时间:2015-01-13 01:48:08

标签: django django-templates

我在模板中有以下内容 -

<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个字符。

我意识到截断它是正确的方法,因为我不想要&#34; ...&#34;那么如何将6个字符的字符串缩短为4?

1 个答案:

答案 0 :(得分:2)

您无法将过滤器应用于模板标记的输出。在主干版本的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]