Source code for djangojs.templatetags.js
# -*- coding: utf-8 -*-
'''
Provide template tags to help with Javascript/Django integration.
'''
from django import template
from django.contrib.staticfiles.storage import staticfiles_storage
from djangojs import JQUERY_MIGRATE_VERSION
from djangojs.conf import settings
register = template.Library()
[docs]class VerbatimNode(template.Node):
'''
Wrap {% verbatim %} and {% endverbatim %} around a
block of javascript template and this will try its best
to output the contents with no changes.
::
{% verbatim %}
{% trans "Your name is" %} {{first}} {{last}}
{% endverbatim %}
'''
def __init__(self, text_and_nodes):
self.text_and_nodes = text_and_nodes
def render(self, context):
output = ""
# If its text we concatenate it, otherwise it's a node and we render it
for bit in self.text_and_nodes:
if isinstance(bit, basestring):
output += bit
else:
output += bit.render(context)
return output
@register.tag
[docs]def verbatim(parser, token):
'''Renders verbatim tags'''
text_and_nodes = verbatim_tags(parser, token, 'endverbatim')
return VerbatimNode(text_and_nodes)
@register.simple_tag
def js_lib(filename):
return '<script type="text/javascript" src="%s"></script>' % staticfiles_storage.url('js/libs/%s' % filename)
@register.simple_tag
[docs]def javascript(filename):
'''A simple shortcut to render a ``script`` tag to a static javascript file'''
return '<script type="text/javascript" src="%s"></script>' % staticfiles_storage.url(filename)
@register.simple_tag
[docs]def js(filename):
'''A simple shortcut to render a ``script`` tag to a static javascript file'''
return javascript(filename)
@register.simple_tag
[docs]def css(filename):
'''A simple shortcut to render a ``link`` tag to a static CSS file'''
return '<link rel="stylesheet" type="text/css" href="%s" />' % staticfiles_storage.url(filename)
def _boolean(value):
if isinstance(value, bool):
return value
elif isinstance(value, (str, unicode)):
return value.lower() == 'true'
elif isinstance(value, int):
return value != 0
else:
return False
@register.simple_tag
[docs]def jquery_js(version=None, migrate=False):
'''A shortcut to render a ``script`` tag for the packaged jQuery'''
version = version or settings.JQUERY_VERSION
libs = [js_lib('jquery-%s.min.js' % version)]
if _boolean(migrate):
libs.append(js_lib('jquery-migrate-%s.min.js' % JQUERY_MIGRATE_VERSION))
return '\n'.join(libs)
@register.inclusion_tag('djangojs/django_js_tag.html', takes_context=True)
[docs]def django_js(context, jquery=True, i18n=True, crsf=True):
'''Include Django.js javascript library in the page'''
return {
'js': {
'jquery': _boolean(jquery),
'i18n': _boolean(i18n),
'crsf': _boolean(crsf),
}
}