0

I have a CSS file which is being used in my template file

<link href="{% static "assets/style/reset.css" %}" rel="stylesheet" type="text/css"/>

I want to access the 'static' in my JavaScript. Is it possible? How can I do it?

syv
  • 3,528
  • 7
  • 35
  • 50

1 Answers1

0

Your javascript has to pass through django's template redering. You could do this by rendering your javacript inside of your template like Django Template Variables and Javascript suggests.


Or you could create a view that just renders your javascript dynamically:

(r'^dynamic.js$', dynamic_js)


def dynamic_js(request):
   """
   Create a js file dynamically      
   """   
   return render(request, 'dynamic.js', 
                 content_type='application/javascript')


# dynamic.js    
# can use template tags now!

Having django serve your static assests is extremely inneffiecient, and is one of the first things to migrate away from if you want a speedy site. If your js file is rarely changing it might be better to create some sort of build process where you can generate your dynamic js with django (so you can use the template variables) and save it to you static folder, so that your webserver can serve the content for you!

Community
  • 1
  • 1
dm03514
  • 54,664
  • 18
  • 108
  • 145
  • See also another related question and anwers here http://stackoverflow.com/questions/9576675/passing-static-url-to-file-javascript-with-django – yellowcap Sep 30 '15 at 12:29