Reputation: 926
When I did something like this:
$("#show").click(function(){
{% for p in collection %}
options.push({
'href' : '{{ p.id }}',
});
{% endfor %}
});
I can retrieve the value of Django template variable.
However, when I was trying to do on other part:
$('[name=test]').live('click', function() {
alert('{{ current_state }}');
var msg = '<div class="userName"> {{ current_user }} </div>';
alert('Message' + msg);
});
I can't retrieve the value of Django template variable from this.
What went wrong from here? I have had this problem sometimes retrieving Django template variable in javasript / jQuery.
EDIT
When I execute following lines on top of everything else, the whole javasript is not working. Any idea why?
$('body').data('current_user_id', {{ current_user_id }});
$('body').data('current_user', {{ current_user }});
Upvotes: 2
Views: 4163
Reputation: 11
your approach worked for me too, however I was accessing the variables in the same page where my jQuery library was getting loaded. In my views:
from myapp.models import MyModel
from django.views.generic import TemplateView
class HomeView(TemplateView):
template_name = 'base.html'
def get_context_data(self, **kwargs):
rows = MyModel.objects.filter(title_slug='titleslug')
context = super(HomeView, self).get_context_data(**kwargs)
context['myvariables'] = []
for row in rows
context['myvariables'].append(row.somefieldval)
return context
In my template:
<script>
options = []
{% for var in myvariables %}
imagesurls.push('{{var|safel}}');
{% endfor %}
alert(options);
</script>
Upvotes: 0
Reputation: 926
I've figured out what went wrong. It was because of the Ajax load used. So, when the main page requested for the page to be loaded into a tag with Ajax load, the Django template variable only displayable from the sub page, but the javascript was written in main page.
Hence, to solve it, the template variables have to be passed into the main page instead of the sub page.
Upvotes: 0
Reputation: 12195
Normally, the JS file is totally static, and as such, you can't insert Django variables into it -- it doesn't work like that.
One approach you could take is to have Django 'park' the variables needed for the JS in your rendered HTML template and then you can grab them and use them in the JS code as required
eg, in the template that uses the javascript in your example, add:
<script type="text/javascript">
// attach variables from Django to the body node of the document
$('body').data('current_state', {{current_state}});
$('body').data('current_user', {{current_user}});
</script>
and then in your JS, pull the value from the data map:
$('[name=test]').live('click', function() {
alert($('body').data('current_state'));
var msg = '<div class="userName">' + $('body').data('current_user') + '</div>';
alert('Message' + msg);
});
If you don't know about $.data(), read this
Upvotes: 6