3 from django import template
4 from django.utils.encoding import smart_unicode
5 from django.utils.safestring import mark_safe
7 from filebrowser.fb_settings import SELECT_FORMATS
9 register = template.Library()
12 @register.inclusion_tag('filebrowser/include/_response.html', takes_context=True)
13 def query_string(context, add=None, remove=None):
15 Allows the addition and removal of query string parameters.
17 _response.html is just {{ response }}
20 http://www.url.com/{% query_string "param_to_add=value, param_to_add=value" "param_to_remove, params_to_remove" %}
21 http://www.url.com/{% query_string "" "filter" %}filter={{new_filter}}
22 http://www.url.com/{% query_string "sort=value" "sort" %}
24 # Written as an inclusion tag to simplify getting the context.
25 add = string_to_dict(add)
26 remove = string_to_list(remove)
27 params = context['query'].copy()
28 response = get_query_string(params, add, remove)
29 return {'response': smart_unicode(response)}
32 def query_helper(query, add=None, remove=None):
34 Helper Function for use within views.
36 add = string_to_dict(add)
37 remove = string_to_list(remove)
39 return get_query_string(params, add, remove)
42 def get_query_string(p, new_params=None, remove=None):
44 Add and remove query parameters. From `django.contrib.admin`.
46 if new_params is None:
56 for k, v in new_params.items():
57 if k in p and v is None:
61 return mark_safe('?' + '&'.join([u'%s=%s' % (k, v) for k, v in p.items()]).replace(' ', '%20'))
64 def string_to_dict(string):
68 {{ url|thumbnail:"width=10,height=20" }}
69 {{ url|thumbnail:"width=10" }}
70 {{ url|thumbnail:"height=20" }}
77 args = (arg.strip() for arg in string.split(',') if not arg.isspace())
78 kwargs.update(arg.split('=', 1) for arg in args)
83 def string_to_list(string):
87 {{ url|thumbnail:"width,height" }}
93 # ensure at least one ','
95 for arg in string.split(','):
103 class SelectableNode(template.Node):
104 def __init__(self, filetype, format):
105 self.filetype = template.Variable(filetype)
106 self.format = template.Variable(format)
108 def render(self, context):
110 filetype = self.filetype.resolve(context)
111 except template.VariableDoesNotExist:
114 format = self.format.resolve(context)
115 except template.VariableDoesNotExist:
117 if filetype and format and filetype in SELECT_FORMATS[format]:
119 elif filetype and format and filetype not in SELECT_FORMATS[format]:
123 context['selectable'] = selectable
127 def selectable(parser, token):
130 tag, filetype, format = token.split_contents()
132 raise TemplateSyntaxError("%s tag requires 2 arguments" % token.contents.split()[0])
134 return SelectableNode(filetype, format)
136 register.tag(selectable)