peterbe / django-static

Template tags for better serving static files from templates in Django
BSD 2-Clause "Simplified" License
193 stars 28 forks source link

I have added a feature to allow django template tags and filters within javascript and stylesheet files #13

Closed panuta closed 13 years ago

panuta commented 13 years ago

https://github.com/panuta/django-static

I think this is a useful feature so I want to share it here.

This feature is to allow adding django template tags and filters like {% url url_name %} or {{value|filter}} within javascript and stylesheet files. For example, based on my own use case, I want to use {% url url_name %} within a javascript file to specify where to make an ajax request to. It is convenient for me because I'll only have to deal with this url only in urls.py file.

I implemented this feature by using render function from django.template.Template to render JS and CSS string just before django-static calling optimize function. It will only render when optimize_if_possible is True and only for JS and CSS files. There's also a limitation that you can't use context variables from request object.

What do you think?

peterbe commented 13 years ago

Personally I think it's a bad idea. I know what you're trying to achieve. I often have code that looks like this:

    <script>CONFIG_URLS.post_user_settings = '{% url something %}';</script>
    <script src="{% slimfile "/js/someajaxstuff.js" %}"></script>

That way the js files are 100% pure of Python or Django or anything like that. If you're .js files aren't .js files really you can't run a linter (e.g. Google Closure Linter) on it.

Also, I think it's not impossible that the URL changes (or worse, becomes dynamic) but the .js file might now be uploaded into a CDN or cached aggressively in Nginx or something.

I would strongly suggest not to put URLs into .js files

panuta commented 13 years ago

True. I never use linter to clean javascript code, so I don't foresee this problem.