views:

295

answers:

2

In my project I have a lot of Ajax methods, with external client-side scripts (I don't want to include JavaScript into templates!) and changing URLs is kind of pain for me because I need to change URLs in my Ajax calls manually.

Is there is some way to emulate the behavior of {% url %} templatetag in JavaScript?

For example, print urlpatterns starting with ^ajax and later in scripts replace patterns with their actual values?

That's what on my mind, and my question is - are there any common practices to do things like that? Maybe some reusable applications? Also I will be happy to read any advices and relevant thoughts you have.

Update 1: I'm talking about computed URLs, not static ones:

url(r'^ajax/delete/(?P<type>image|audio)/(?P<item_id>\d+)/from/set/(?P<set_id>\d+)/$', 'blog.ajax.remove_item_from_set'),
A: 

What I usually do is put the URL in either an <input type="hidden" /> element, or in the rel="" attribute.

Then, when writing the JS (using jQuery below) I do:

$('div#show_more').click(function () {
    var url = $(this).attr('rel');
    // or
    var url = $('#more_url').val();

    $.get(url, function () { /* ... */ });
});

Nonstandard attributes are well supported by all major browsers and hidden elements don't have to be in forms.

Emil Ivanov
What would you do with computed urls? url(r'^ajax/delete/(?P<type>image|audio)/(?P<item_id>\d+)/from/set/(?P<set_id>\d+)/$', 'blog.ajax.remove_item_from_set'),
dir01
You put them somewhere on the page (in the django template) - the javascript is a separate file that is not generated by django.
Emil Ivanov
+4  A: 

What's wrong with putting JavaScript in your templates?

You often want to call an initialisation function in your HTML template anyway, so why not pass it an object containing URLs you'll be using?

<script>
MYGLOBAL.mymodule.init({
    fancy_ajax_url: '{% url fancy %}',
    fancier_ajax_url: '{% url fancier %}'
});
</script>

If you find yourself passing a lot of variable this way, or wanting to use logic in your JavaScript that you do in your HTML templates, then why not render your script through Django's templating engine? Remember, Django templates are not just for HTML documents - often it helps to use templates for plain text, XML, JSON, and yes even JavaScript. Worried about performance? Then cache the result.

ozan
That are initials of my task, so face it ) JS files would be delivered thru CDN. What I can do is to put urlpatterns on the top of my page (set js variables) and compile real urls from regexps with real data
dir01