javascript - Django; adding variable to media files in a custom widget -


i want make widget has media files, , want able pass in parameters media files have access to.

# in forms.py class acustomwidget(forms.textinput):     class media:         css = {             'all': ('pretty.css',)         }         js = ('animations.js',) 

for example, within animation.js have {{ my_variable }}. question is, how populate {{ my_variable }} inside 'animation.js' in manner this:

# in forms.py class myform(forms.form):     a_field = acustomwidget(my_variable="#_a_string_variable") 

thank , feel free request clarifications.

you can't add variable js file because js not parsed template. it's static. way can pass variable in include in inline script in template code:

<script type="text/javascript">     var my_variable = '{{ my_variable }}`; </script> 

however, django doesn't use template parser on widget code. default render methods return straight ready-to-go html. that's not problem; have approach differently.

so, first, need able accept variable in instantiation of widget. can so:

class acustomwidget(forms.textinput):     def __init__(self, *args, **kwargs):         self.my_variable = kwargs.pop('my_variable')         super(acustomwidget, self).__init__(*args, **kwargs) 

then, in render method, can access instance variable add output:

from django.utils.safestring import mark_safe  ...  def render(self, name, value, attrs):     output = super(acustomwidget, self).render(name, value, attrs)     if self.my_variable not none:         output += u'<script type="text/javascript">var my_variable = "%s";</script>' % self.my_variable     return mark_safe(output) 

finally, in js utilize global variable. you'll need make sure code runs after page done rendering variable available. also, since you're dealing global var here, should take care name it.


Comments