Commits

David Townshend committed d0466c7

Add toggle_params functions

Comments (0)

Files changed (4)

tests/test_toggle_params.py

+from __future__ import absolute_import, unicode_literals
+
+from unittest import TestCase
+
+from url_tools.templatetags.urls import toggle_params
+
+
+class toggleParamsTestCase(TestCase):
+    def test_toggle_params_basic(self):
+        self.assertEqual(toggle_params('/foo/?foo=1', foo=1), '/foo/')
+
+    def test_toggle_params_multiple(self):
+        self.assertEqual(toggle_params('/foo/?foo=1', foo=1, bar=2), '/foo/?bar=2')

tests/test_url_helper.py

         u1 = UrlHelper('/foo/bar?foo=1&bar=2')
         u2 = UrlHelper(u1)
         self.assertEqual(u2.get_full_path(), '/foo/bar?foo=1&bar=2')
+
+    def test_toggle_params_disable(self):
+        u = UrlHelper('/foo/bar?foo=1')
+        u.toggle_params(foo=1)
+        self.assertEqual(u.get_full_path(), '/foo/bar')
+
+    def test_toggle_params_enable(self):
+        u = UrlHelper('/foo/bar?foo=1')
+        u.toggle_params(bar=1)
+        self.assertEqual(u.get_full_path(), '/foo/bar?foo=1&bar=1')
+
+    def test_toggle_params_toggle_multiple(self):
+        u = UrlHelper('/foo/bar?foo=1')
+        u.toggle_params(foo=1, bar=1)
+        self.assertEqual(u.get_full_path(), '/foo/bar?bar=1')

url_tools/helper.py

                            if not x.startswith(val)]
                 self.query_dict.setlist(key, to_keep)
 
+    def toggle_params(self, **params):
+        for param, value in params.items():
+            value = unicode(value)
+            if value in self.query_dict.getlist(param):
+                self.del_params(**{param: value})
+            else:
+                self.overload_params(**{param: value})
+
     @property
     def hash(self):
         md5 = hashlib.md5()

url_tools/templatetags/urls.py

     return u.get_full_path()
 
 
+@register.simple_tag
+def toggle_params(url, **kwargs):
+    u = UrlHelper(url)
+    u.toggle_params(**kwargs)
+    return u.get_full_path()
+
+
 @register.filter(name='quote')
 def quote_param(value, safe='/'):
     return urllib.quote(value, safe)