killerbarney
killerbarney

Reputation: 943

Django - Template tags in javascript and css files

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.

Upvotes: 9

Views: 7587

Answers (4)

dmvianna
dmvianna

Reputation: 15730

How 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.

Upvotes: 1

thnee
thnee

Reputation: 5927

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.

Upvotes: 0

Bob
Bob

Reputation: 3351

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 "compile" 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.

Upvotes: 0

Manoj Govindan
Manoj Govindan

Reputation: 74795

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.

Upvotes: 0

Related Questions