Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 713
jobima Avatar asked Aug 24 '15 12:08

jobima


People also ask

What is Django simple tag?

Django provides custom template tags to improve data processing, code reusability, and the general structure of a project. Simple_tag : Processes the data and returns a string. It can be very useful to revrieve some description of a queryset. For example, the count() method of a queryset.

How to register a tag in Django?

Registering the tagThe tag() method takes two arguments: The name of the template tag – a string. If this is left out, the name of the compilation function will be used. The compilation function – a Python function (not the name of the function as a string).

What is template inheritance in Django?

Template inheritance. The most powerful – and thus the most complex – part of Django's template engine is template inheritance. Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override.


1 Answers

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.

like image 190
Shang Wang Avatar answered Nov 05 '22 18:11

Shang Wang