2

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 }});
2
  • Are both of those code snippets from same file? Commented Dec 19, 2011 at 11:39
  • not really from the same file. Commented Dec 19, 2011 at 17:31

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

5 Comments

I've edited my question. Do you know what went wrong? I've read the documentation and the syntax was indeed correct.
So, i'm assuming that your JS is inline in the template file; given that, check what variables are being passed to the template. Are you sure that current_user and current_state are being passed in?
Yup. I've tried to displayed those variables value on DOM elements. That was why I was confused how javascript works with those template variables as I mentioned, the first code snippet was working fine.
What does your browser console say? Do you have a <body> tag in your document, if not, either add one or change it to $(document).data(........)
Hi there, I've posted my answer as what was the exact problem I found out. Thanks anyway. Appreciate your help and it's certainly helpful in future usage. :)
0

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.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.