Created
July 8, 2010 17:09
-
-
Save rctay/468316 to your computer and use it in GitHub Desktop.
[django] javascript widget factory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Inserts JavaScript, rendered with the context built from a widget's attributes, | |
after a widget's rendered HTML. | |
""" | |
from django.forms.widgets import Widget | |
from django.template import Template | |
from django.template.context import Context | |
from django.utils.safestring import mark_safe | |
def javascript_widget_factory(script, base_cls=Widget): | |
class _JavaScriptWidget(base_cls): | |
_script_template = Template(script) | |
def render(self, name, value, attrs=None, choices=()): | |
str = super(_JavaScriptWidget, self).render(name, value, attrs, choices) | |
str_js = self._script_template.render(Context(attrs)) | |
return mark_safe(str + '<script type="text/javascript">' + str_js + '</script>') | |
return _JavaScriptWidget |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment