[Fixed]-Put the result of simple tag into a variable

23👍

Please use assignment tag if you are using django < 1.9. The doc is here. I posted the example in the docs here:

@register.assignment_tag
def get_current_time(format_string):
    return datetime.datetime.now().strftime(format_string)

Then in template:

{% get_current_time "%Y-%m-%d %I:%M %p" as the_time %}
<p>The time is {{ the_time }}.</p>

You can see that the template tag result becomes a variable using as statement. You can use the_time however you like, including if statement.

Also quote from the docs:

Deprecated since version 1.9: simple_tag can now store results in a
template variable and should be used instead.

0👍

Since Django >=2.0, please use simple_tag:

@register.simple_tag
def get_current_time(currency):
    return datetime.datetime.now().strftime(format_string)

Then in the template:

{% get_current_time "%Y-%m-%d %I:%M %p" as the_time %}
<p>The time is {{ the_time }}.</p>
👤PMC

Leave a comment