Jed Fox
Jed Fox

Reputation: 3025

How can I include template tags in static files in Django?

I would like to be able to DRY out my static files by using a template tag, like {% url 'my_view' %}, in my static file, instead of /path/to/my_view. Is there a way to do this?

Upvotes: 1

Views: 981

Answers (1)

danielcorreia
danielcorreia

Reputation: 2136

Short answer is no. But you can circumvent this, there's two approaches I can think of:

  1. add a script with the urls you need in your base html template, they need to be available globally so that you can access them with other scripts
  2. make a script to generate a .js file with all your urls and place it with all the other staticfiles (django translations for js use a similar approach)

Approach 1, would be something like:

<html>
...
<script>
  var myApp = {
    URLS: {
      login: {% url 'login' %},
      welcome: {% url 'welcome' %},
      ...
    }
  }
</script>
<script>console.log("The login url is " + myApp.URLS.login + "!")</script>
<script src="script/that/uses/urls.js"></script>
...
</html>

Upvotes: 2

Related Questions