On Tue, Mar 5, 2013 at 4:57 PM,  <7equivale...@gmail.com> wrote:
> Well, I definitly can't just throw a variable into the Javascript using the
> {{ }} tags. I tried it and it didn't work. I'm sure Shawn Milochik is
> correct about consuming the view with AJAX, however that is going to take
> sometime to learn and explore, as I am novice at this. It seems there should
> be an easy way for something so simple, I can pass a variable from a view to
> a template, but not from a view to a javascript file.
>

This is not true. You can render your javascript using a template if
you like, templates can be used to generate any textual format. A view
is simply a function that takes a request and produces a single
resource as a response.

However people don't normally dynamically generate their JS. This is
because it is not necessary, you simply include the data you want into
the HTML that the javascript will run against. You then use standard
JS methods to extract the data that you need and use it.

Eg, if you wanted to trigger an AJAX request each time someone clicked
a <li>, you might do something like this:

<ul>
  <li>Hello World</li>
  <li>Wibble<li>
</ul>

Your JS file may have something like this:

$('ul li').click(function(ev) {
  $.getJSON( '{{ some-url }}', json_handler);
}

Obviously the "{{ some-url }}" would not work. Instead, the data can
be inserted in to the HTML element to which it refers:

<ul>
  <li data-json-uri="/json/foo/bar/1">Hello World</li>
  <li data-json-uri="/json/foo/bar/2">Wibble<li>
</ul>

and now the JS can be written to query that data:

$('ul li').click(function(ev) {
  $.getJSON(ev.target.data('json-uri'), json_handler);
}

tl;dr - if you need data in your javascript files, insert it into the
HTML doc and extract it when you need it.

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to