Skip to content

Instantly share code, notes, and snippets.

@barseghyanartur
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barseghyanartur/4aa87c34a30a364b9311 to your computer and use it in GitHub Desktop.
Save barseghyanartur/4aa87c34a30a364b9311 to your computer and use it in GitHub Desktop.
A Django template filter to render the media files (JS and CSS) separately, instead of all together in just one place.
When you render the forms media, it puts all JS and CSS files in one place. Quite often you want to
have CSS to be rendered in the top of the page and JS at the bottom.
Below - a Django template filter to render the media files (JS and CSS) separately, instead of all
together in just one place.
In that way you can do the following in your template:
.. code-block:: html
<html>
<head>
...
{{ feincms_page.content.media.render_css|render_assets }}
</head>
<body>
...
{{ feincms_page.content.media.render_js|render_assets }}
</body>
</html>
The template filter:
.. code-block:: python
from itertools import chain
from django.utils.safestring import mark_safe
from django import template
register = template.Library()
@register.filter
def render_assets(assets):
"""
The `django.forms.widgets.Media` has nice method `render`, which does
render all the assets. However, it's not possible to render just CSS
or JS files properly. This filter fixes that gap.
"""
return mark_safe(u'\n'.join(chain(*[assets])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment