Commits

Gregory Petukhov committed 5ba0f23

Add `set` template tag. Add progress library

Comments (0)

Files changed (3)

common/progress.py

+import sys
+
+class Progress(object):
+    def __init__(self, step=None, total=None, stop=None, name='items'):
+        if not total and not step:
+            raise Exception('Both step and total arguments are None')
+        if total and not step:
+            step = int(total / 20)
+        self.step = step
+        self.count = 0
+        self.total = total
+        self.stop = stop
+        self.name = name
+    
+    def tick(self):
+        self.count += 1
+        if not self.count % self.step:
+            if self.total:
+                percents = ' [%d%%]' % int((self.count / float(self.total)) * 100)
+            else:
+                percents = ''
+            print 'Processed %d %s%s' % (self.count, self.name, percents)
+        if self.count == self.stop:
+            print 'Reached stop value %d' % self.stop
+            sys.exit()

common/templatetags/common_tags.py

 # -*- coding: utf-8
+"""
+Template tags:
+ * alter_qs - allows to modify arguement in URL query string
+ * set - allows to set new variable in template
+
+Credits:
+ * code for `set` tag is based on http://djangosnippets.org/snippets/215/
+"""
 from cgi import parse_qsl
 from urllib import urlencode
 
 def alter_qs(qs, name, value, name2=None, value2=None):
     """
     Alter query string argument with new value.
+
+    Usage in template:
+        <a href="/foo/bar{% alter_qs request.META.QUERY_STRING "page" 3 %}">Some link</a>
+
+    Usage in code:
+        from common.templatetags.common_tags import alter_qs
+        url = alter_qs(some_url, "page", "4")
     """
 
     qs = qs.lstrip('?')
             return result
     else:
         return ''
+
+
+
+@register.tag(name='set')
+def do_set_varable(parser,token):
+    """
+    Set new value in the context of template.
+
+    Usage:
+        {% set category_list category.categories.all %}
+        {% set dir_url "../" %}
+        {% set type_list "table" %}
+        {% include "category_list.html" %}
+    """
+    from re import split
+    bits = split(r'\s+', token.contents, 2)
+    return SetVariableNode(bits[1],bits[2])
+
+
+class SetVariableNode(template.Node):
+    """
+    Template Node of `set` tag.
+    """
+
+    def __init__(self,varname,value):
+        self.varname = varname
+        self.value = value
+    
+    def render(self,context):
+        var = template.resolve_variable(self.value,context)
+        if var:
+            context[self.varname] = var
+        else:
+            context[self.varname] = context[self.value]
+        return ''
 from setuptools import setup
 
 PACKAGE = 'common'
-VERSION = '0.1.37'
+VERSION = '0.1.38'
 
 if __name__ == '__main__':
     # Compile the list of packages available, because distutils doesn't have