Created
June 19, 2012 08:56
-
-
Save zen4ever/2953100 to your computer and use it in GitHub Desktop.
SpanWidget
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
class SpanWidget(forms.Widget): | |
""" | |
Renders a value wrapped in a <span> tag. | |
Based on Killarny, http://www.djangosnippets.org/snippets/1340/ | |
Modified to place the value in a hidden control, so that it | |
returns a value in the GET/POST response. | |
""" | |
def __init__(self, attrs=None, choices=(), url=False): | |
super(SpanWidget, self).__init__(attrs=attrs) | |
self.url = url | |
self.choices = list(choices) | |
def get_hidden(self, name, value): | |
return "<input type='hidden' name='%s' value='%s' />" \ | |
% (name, escape(value).replace('\n',' ').replace('\r',' ')) | |
def get_render_value(self, value): | |
render_value = value | |
if self.choices: | |
render_value = dict(self.choices).get(value, '') | |
return render_value | |
def render(self, name, value, attrs=None): | |
final_attrs = self.build_attrs(attrs, name=name) | |
render_value = self.get_render_value(value) | |
if hasattr(value, 'url'): | |
return mark_safe(u"<span%s><a href='%s'>%s</a></span>" % ( | |
forms.util.flatatt(final_attrs), | |
escape(striptags(unicode(value.url))), | |
escape(striptags(unicode(value.name.rsplit('/', 1)[1]))), | |
)) | |
hidden = self.get_hidden(name, value) | |
return mark_safe(u"<span%s>%s%s</span>" % ( | |
forms.util.flatatt(final_attrs), | |
escape(striptags(unicode(render_value))), | |
hidden)) | |
class URLSpanWidget(SpanWidget): | |
def render(self, name, value, attrs=None): | |
final_attrs = self.build_attrs(attrs, name=name) | |
render_value = self.get_render_value(value) | |
hidden = self.get_hidden(name, value) | |
render_value = value[:55] | |
if render_value != value: | |
render_value += "..." | |
return mark_safe(u"<span%s><a href='%s'>%s%s</a></span>" % ( | |
forms.util.flatatt(final_attrs), | |
escape(striptags(unicode(value))), | |
escape(striptags(unicode(render_value))), | |
hidden, | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment