1. Hadi Moshayedi
  2. djangodash2011

Commits

Hadi Moshayedi  committed 6c9e7c6

Added js_urls

  • Participants
  • Parent commits 2ed3598
  • Branches default

Comments (0)

Files changed (3)

File goalrally/goal_tracking/templatetags/__init__.py

Empty file added.

File goalrally/goal_tracking/templatetags/gt_tags.py

View file
+# ------------------------------------------------------------------------------
+from django import template
+from django.conf import settings
+from goalrally.urls import urlpatterns
+import re, json
+register = template.Library()
+
+# ------------------------------------------------------------------------------
+def js_normal_url(url, context):
+    url = "/" + url[1:]
+    if url[-1] == '$':
+        url = url[:-1]
+    repl = lambda m: "{" + m.groupdict()['name'] + "}"
+    url = re.sub(r"\(\?P\<(?P<name>\w+)\>[^)]+\)", repl, url)
+    if "localeurl" in settings.INSTALLED_APPS:
+        url = "/" + context['request'].LANGUAGE_CODE + url
+    return url
+
+# ------------------------------------------------------------------------------
+@register.simple_tag(takes_context=True)
+def js_urls(context):
+    q = [(urlpatterns, '^')]
+    result = {}
+    idx = 0
+    while idx < len(q):
+        patterns, prefix = q[idx]
+        for p in patterns:
+            pat = p.regex.pattern
+            if pat and pat[0] == '^': pat = pat[1:]
+            if hasattr(p, 'url_patterns'):
+                if p.app_name != 'admin':
+                    q.append((p.url_patterns, prefix + pat))
+            elif p.name:
+                result[p.name] = js_normal_url(prefix + pat, context)
+        idx += 1
+    output = """
+        var django_urls = %(urls)s;
+        function url_reverse(name, args) {
+            var url = django_urls[name];
+            for(a in args) {
+                url = url.replace("{" + a + "}", args[a]);
+            }
+            return url;
+        }
+    """ % {'urls': json.dumps(result)}
+    return output
+
+# ------------------------------------------------------------------------------

File goalrally/templates/base/base.html

View file
+{% load gt_tags %}
 <!DOCTYPE html> 
 <html> 
     <head>
         <script src="{{ MEDIA_URL }}js/jquery-ui.js" type="text/javascript" language="javascript" charset="utf-8"></script>
         <script src="{{ MEDIA_URL }}js/less.js" type="text/javascript" language="javascript" charset="utf-8"></script>
         <script src="{{ MEDIA_URL }}js/elastic.js" type="text/javascript" language="javascript" charset="utf-8"></script>
+        <script type="text/javascript">
+            {% js_urls %}
+            var MEDIA_URL = "{{ MEDIA_URL }}";
+            var csrf_token = "{{ csrf_token }}";
+        </script>
     </head>
     <body>
         <div class="unit header">