0

{{ form.media.js }} and {{ form.media.css }} are great to easily include media in Django templates.

My problem is that I would like to get access to the raw urls (without <\script type="text/javascript" src="raw_url"><\/script>) of these media (to include them using headjs).

I'd like to achieve something like that:

<script>
{% for script in form.media.js %}
    head.js("{{ script.raw_url }}");
{% endfor %}
</script>
5
  • Moreover, calling head.js as many times as many scripts you have, won't give you any benefit. headjs.com Jun 26, 2013 at 9:53
  • I think you did not understand my question: "{{ script.raw_url }}" does not exist in django. You just have a block {{ form.media.js }}, which is replaced by: <\script type="text/javascript" src="url1"><\script>... I'd like to get this "url1"
    – gueux
    Jun 26, 2013 at 9:56
  • And I want to call head.js this way for scripts to be loaded in parallel.
    – gueux
    Jun 26, 2013 at 9:59
  • I just found this url, which explains the same problem as mine: groups.google.com/forum/#!topic/django-developers/QD1wSWV3qEQ does not seem to have any solution :(
    – gueux
    Jun 26, 2013 at 10:03
  • @geux, I know you want to call head.js but i posted a link to documentation in my comment - you should call it once like head.js(script_url_1, script_url_2, ..., script_url_n, optional_callback). Your loop would output multiple calls of head.js. Jun 26, 2013 at 10:26

1 Answer 1

4

If you take a look at source code of Media class there will be a function:

def render_js(self):
    return [u'<script type="text/javascript" src="%s"></script>' % self.absolute_path(path) for path in self._js]

So you can go the same way. Since we can't use underscored attributes in templates we can add method to the form class like this and use it:

from django import forms

class TestForm(forms.Form):
    def get_media_js(self):
        return [self.media.absolute_path(path) for path in self.media._js]

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.