Is there any way to add template tags into javascript and css files? I would use it for anything from passing in urls to media url links (image paths, etc) to conditional javascript based on user permissions.
I just had a thought that maybe I can serve it up as if it were a template but have the url as my javascript file. Is that the only way to do somethign like this? If so, it probably wouldn't work with my media generator, so I'd probably want a better solution if there was one out there.
Is there any way to add template tags into javascript and css files? I would use it for anything from passing in urls to media url links (image paths, etc) to conditional javascript based on user permissions.
I just had a thought that maybe I can serve it up as if it were a template but have the url as my javascript file. Is that the only way to do somethign like this? If so, it probably wouldn't work with my media generator, so I'd probably want a better solution if there was one out there.
Share Improve this question asked Aug 23, 2010 at 18:23 killerbarneykillerbarney 94310 silver badges24 bronze badges4 Answers
Reset to default 1How about defining the JavaScript variables and CSS attributes from within your Django HTML template, between script and style tags? I know it sounds like a hack, but it seems to me a tidy one, as this will allow you to control your dynamic variables from one spot.
Your idea is the right way to go. If you want to leverage Django's template tools then the easiest way is to serve up the JS file as a template. See this question for a situation like yours.
You can serve any type of content like a template, it doesn't have to be HTML. However, you may not be able to serve it with the rest of your static content, depending on your setup.
One option, if you only want to replace things like media URLs, is to "pile" these templates into static files that you can serve. This won't work for anything that is conditional based on the current user's permissions, though. You'll need to write a script to call django.template.loader.render_to_string
and write the result to a file every time you deploy or change media URLs, etc.
As for dynamic content inside JS-files, you would have to make a template, like the others said.
But you can very easily attach JS and CSS files to specific page templates using django-sekizai. (I use it as a part of django-cms, but it works stand alone too.)
It allows you to, inside a normal page template, define the template's required static resources in a block. There is one block for CSS and one for JS. These blocks can then be printed in your base.html. It also handles duplicates, so you don't have to worry about adding the same files multiple times. See the usage document.
With this system, you wont be sending any restricted JS or CSS, since django will only run authorized templates, and the content will never be added to the JS and CSS blocks.