pythondjangodjango-templatestemplatetag

Put the result of simple tag into a variable


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


Solution

  • 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.