whoisearth
whoisearth

Reputation: 4170

django template tag shorten string

I have the following in a template -

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

It's giving me an error

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

{% now "u" %} does display correctly the problem is that by default it displays 6 characters and I only want it to display 4 characters.

I'm realizing that truncatechars it's the right way to do it because I don't want the "..." so how do I go about shortening the string of 6 characters to be only 4?

Upvotes: 0

Views: 274

Answers (1)

catavaran
catavaran

Reputation: 45575

You can't apply a filter to template tag's output. In trunk version of django {% now %} tag can save formatted time to variable:

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

But in the current stable django (1.7.2) the as keyword is not supported.

So you have to write custom template tag. It is easy:

import datetime
from django import template

register = template.Library()

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

Upvotes: 2

Related Questions