Put the result of simple tag into a variable
Asked Answered
A

2

15

this works:

{% get_option 'payment_conditions' '' true %}

It calls a function with 3 parameters and it returns a string: "I am the conditions". Great.

What I want to do now is to put this in a IF statement. So to do this, I need the value into a variable. Something like:

{% with conditions = get_option 'payment_conditions' '' true %}

But it does not work. I also tried:

{% get_option 'payment_conditions' '' true as conditions %}

Is there a way that I can place the result into a variable?? Thanks

Ambrosane answered 24/8, 2015 at 12:16 Comment(2)
Is get_option a template tag you defined?Wahkuna
yes, it is defined and it works out of the IF statement.Ambrosane
W
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.

Wahkuna answered 25/8, 2015 at 13:12 Comment(1)
assignment_tag has been removed in Django 2.0Moisture
M
0

Since Django >=2.0, please use simple_tag:

@register.simple_tag
def get_current_time(format_string):
    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>
Madame answered 5/12, 2023 at 9:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.