Calling Jquery or javascript function based on an if condition

1,880 views
Skip to first unread message

Sarfraz ahmad

unread,
Apr 23, 2013, 4:30:38 PM4/23/13
to django...@googlegroups.com
Guys, is it possible to call a javascript function in django templates based on an if condition.......?????????? What i want to do is that in django templates if a given if condition is true i want to call a javascript function automatically............

tell me guys if it is possible or not????

der_FeniX

unread,
Apr 23, 2013, 4:45:20 PM4/23/13
to django...@googlegroups.com, Sarfraz ahmad

{% if condition %}

<script type="text/javascript">

some_function(params);

</script>

{% endif %}



Sarfraz ahmad wrote at 23 апреля 2013 13:30:38:

Iftikhar Ali

unread,
Apr 25, 2013, 10:32:59 AM4/25/13
to django...@googlegroups.com
yes brother you can it is very easy
just put your condition in and if
you should have to know how the if condition is working in django templates


{% ifequals comparator1 comparator2 %}

call javascript function from here

{% end ifequals %}

Chris Lawlor

unread,
Apr 26, 2013, 8:58:13 AM4/26/13
to django...@googlegroups.com, Sarfraz ahmad
A slight variation of this approach is to map some Django template context info to Javascript variables in one of your templates, making that data accessible to your compressed / minified JS code:

# in a template, "base.html" perhaps..

<script>
window.DjangoContext = {
  userLoggedIn: {{ user.is_authenticated|yesno:"true,false" }}
}
</script>

Note the use of the 'yesno' filter to convert "True" to "true" to match JS syntax.

Now you can access DjangoContext.userLoggedIn anywhere in your JS.


** It's important to note that users can modify any JS variable they wish, so don't rely on something like this for security **
Reply all
Reply to author
Forward
0 new messages