Browse Source

Simple AJAX API on server side

Ralfp 12 years ago
parent
commit
d31756c9e2
2 changed files with 29 additions and 5 deletions
  1. 13 4
      misago/theme.py
  2. 16 1
      misago/utils/views.py

+ 13 - 4
misago/theme.py

@@ -1,5 +1,6 @@
 from django.conf import settings
-from coffin.shortcuts import render, render_to_response
+from coffin.shortcuts import render_to_response
+from coffin.template import dict_from_django_context
 from coffin.template.loader import get_template, select_template, render_to_string
 
 '''Monkeypatch Django to mimic Jinja2 behaviour'''
@@ -35,9 +36,6 @@ class Theme(object):
             prefixed += templates
             return prefixed
 
-    def render(self, request, *args, **kwargs):
-        return render(request, *args, **kwargs)
-
     def render_to_string(self, templates, *args, **kwargs):
         templates = self.prefix_templates(templates)
         return render_to_string(templates, *args, **kwargs)
@@ -46,6 +44,17 @@ class Theme(object):
         templates = self.prefix_templates(templates)
         return render_to_response(templates, *args, **kwargs)
 
+    def macro(self, templates, macro, dictionary={}, context_instance=None):
+        templates = self.prefix_templates(templates)
+        template = select_template(templates)
+        if context_instance:
+            context_instance.update(dictionary)
+        else:
+            context_instance = dictionary
+        context_instance = dict_from_django_context(context_instance)
+        _macro = getattr(template.make_module(context_instance), macro)
+        return unicode(_macro()).strip()
+
     def get_email_templates(self, template, contex={}):
             email_type_plain = '_email/%s_plain.html' % template
             email_type_html = '_email/%s_html.html' % template

+ 16 - 1
misago/utils/views.py

@@ -1,9 +1,24 @@
+from json import dumps as json_dumps
 from django.core.urlresolvers import reverse
+from django.http import HttpResponse
 from django.shortcuts import redirect
+from django.template import RequestContext
 
 def redirect_message(request, message, type='info', owner=None):
     """
     Set flash message and redirect to board index.
     """
     request.messages.set_flash(message, type, owner)
-    return redirect(reverse('index'))
+    return redirect(reverse('index'))
+
+
+def ajax_response(request, template=None, macro=None, vars={}, json={}, status=200, message=None):
+    html = ''
+    if macro:
+        html = request.theme.macro(template, macro, vars, context_instance=RequestContext(request));
+    response = json_dumps(dict(json.items() + {
+                                       'code': status,
+                                       'message': message,
+                                       'html': html
+                                       }.items()), sort_keys=True,  ensure_ascii=False)
+    return HttpResponse(response, content_type='application/json', status=status)