0

I'm using ajax to asynchronously update a boolean variable in my Django project. I'm able to successfully display this variable using the template but I'm not sure how I can use this variable in the template's embedded python logic.

Basically

{% if JSON_BOOL %}

<p>this</p>

{% else %}

<p>that</p>

{% endif %}

Where the JSON_BOOL is being supplied by an ajax function. What's the best way to make the variable available to the conditional logic? Thanks.

Patrick Connors
  • 5,677
  • 6
  • 27
  • 54
  • Possible duplicate of http://stackoverflow.com/questions/23838975/how-to-get-values-from-the-ajax-into-django-template – Arpan Jun 24 '16 at 15:31
  • Pretty similar to what I'm asking, @Arpan, but that answer doesn't specify how I can use the returned JSON as a python variable. Thanks! – Patrick Connors Jun 24 '16 at 15:45
  • Just so I understand your problem, you need to transform a JSON variable being rendered in a template from text to a bool value so you can use it in the conditional logic? – JwM Jun 24 '16 at 18:03
  • @JwM that's my question. – Patrick Connors Jun 24 '16 at 18:47

1 Answers1

1

There are two ways to solve this. If I were you, I would just leave the variable in text format and in your code say:

{% if JSON_BOOL == "True" %}
...
{% else %}
...the rest of your code

Otherwise you could cast it to a boolean on the python side of things. This would look as follows in your view:

if JSON_BOOL == "True":
    JSON_BOOL = True
else:
    JSON_BOOL = False

I'm not aware of a way to cast variables to different types within the template itself..this seems to be outside of its scope of functionality, and either way it's better to keep functionality out of templates. Hope this helps.

JwM
  • 354
  • 2
  • 15