views:

464

answers:

3

As far as I know, there's no way to use {% include %} within a dynamic JS file to include styles. But I don't want to have to make another call to the server to download styles.

Perhaps it would be possible by taking a stylesheet and injecting it into the head element of the document...has anyone does this before?

A: 

I can envision cases where you'd want to dynamically generate JS or CSS, but generally you're better off creating static files for each and making your code general enough to fulfill all your needs.

This goes beyond a simple matter of code reuse - if you're dynamically generating any of this, it will need to be re-downloaded each time it's used. You're wasting CPU time rendering the templates, and wasting bandwidth sending the same (or potentially the same) data over the wire over and over.

But if you have a good use case for meta-coding, there's no reason why you can't either:

a) put the JS or CSS in the header (or body, in the case of JS) of your rendered template b) create a view for the JS or CSS, and use Django's template engine to render them.

The {% include %} tag will work fine for (a), and for (b) you'd just use normal HTML to reference the URL of your view.

Daniel
+3  A: 

In your JS file:

var style = document.createElement('link');
style.setAttribute('rel', 'stylesheet');
style.setAttribute('type', 'text/css');
style.setAttribute('href', 'style.css');
document.getElementsByTagName('head')[0].appendChild(style);

Hope that helps.

Gian Basagre
A: 

With jquery...

$('head').append($('<link rel="stylesheet" type="text/css" href="style.css">'))
rgz