Jay Yu avatar Jay Yu committed 334dee1

attempt to customise piston emitter for JSON template
index template
simple template loader using jQuery.get()

Comments (0)

Files changed (8)

testproject/api/emitters.py

+from django.core.serializers.json import DateTimeAwareJSONEncoder
+from django.utils import simplejson
+
+from piston.emitters import Emitter
+
+class JSONTemplateEmitter(Emitter):
+    """
+    JSON emitter that gives root element a name, to work with 
+    """
+    def render(self, request):
+        cb = request.GET.get('callback')
+        my_dict = {
+            'root': self.construct(),
+        }
+
+        seria = simplejson.dumps(my_dict, cls=DateTimeAwareJSONEncoder, indent=4)
+
+        # Callback
+        if cb:
+            return '%s(%s)' % (cb, seria)
+
+        return seria
+
+Emitter.register('json-template', JSONTemplateEmitter, 'application/json; charset=utf-8')

testproject/api/urls.py

 from piston.resource import Resource
 
 from handlers import EntryHandler
+from emitters import JSONTemplateEmitter
 
 entry_h = Resource(EntryHandler)
 
 urlpatterns = patterns('',
-   url(r'^entry/(?P<entry_id>[^/]+)/', entry_h, { 'emitter_format': 'json' }),
-   url(r'^entry/', entry_h, { 'emitter_format': 'json' }),
+   url(r'^entry/(?P<entry_id>[^/]+)/', entry_h, { 'emitter_format': 'json-template' }),
+   url(r'^entry/', entry_h, { 'emitter_format': 'json-template' }),
 )

testproject/jlog/templates/index.html

-{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1}, "objects": [{"content": "First post!!", "created_date": "2011-11-19T13:49:37.953231", "id": "1", "modified_date": "2011-11-19T13:49:37.953247", "published_date": null, "resource_uri": "/api/v1/post/1/", "slug": "lao-gong-test", "title": "Lao gong test"}]}
-
-{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1}, "objects": [{"author": "/api/v1/author/1/", "content": "First post!!", "created_date": "2011-11-19T13:49:37.953231", "id": "1", "modified_date": "2011-11-19T13:49:37.953247", "published_date": null, "resource_uri": "/api/v1/post/1/", "slug": "lao-gong-test", "title": "Lao gong test"}]}
-
-{.section objects}
-  {.repeated section @}
-  <h2>{title}</h2>
-  <p>Published by {}
-
-  <table width="100%">
-  {.repeated section @}
-    <tr>
-      <td><a href="{url-base|htmltag}{url|htmltag}">Play</a>
-      <td><i>{title}</i></td>
-      <td>{artist}</td>
-    </tr>
-  {.end}
-  </table>
-{.or}
-  <p><em>(No page content matches)</em></p>
-{.end}

testproject/jlog/templates/json-templates/index.html

+<h1>JSON-Template Blog Index</h1>
+
+{.section root}
+  <code>Cursor value is: {@}</code>
+  {.repeated section @}
+  <h2>Title: {title|html}</h2>
+  <h3>Written by: {author.first_name|html} {author.last_name|html}; {published_date}</h3>
+  <p>{content|html}</p>
+  <p><a href="//jayyu.com/blog/{slug|htmltag}">Permalink</a></p>
+  {.or}
+  <h2>ERROR: &ldquo;@&rdquo; not working</h2>
+  {.end}
+{.or}
+  <h2>ERROR: &ldquo;root&rdquo; element not found</h2>
+{.end}

testproject/jlog/urls.py

+from django.views.generic.simple import direct_to_template
 from django.conf.urls.defaults import patterns, include, url
 
+from views import templates_as_json
+
 urlpatterns = patterns('',
-    # Examples:
-    # url(r'^$', 'testproject.views.home', name='home'),
-    # url(r'^testproject/', include('testproject.foo.urls')),
-
-    # Uncomment the admin/doc line below to enable admin documentation:
-    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
-
-    # Uncomment the next line to enable the admin:
-)
+    url(r'^json-templates$', templates_as_json),
+    url(r'^json-templates/index\.html$', direct_to_template, {'template': 'json-templates/index.html'}, name='blog-index'),
+)

testproject/jlog/views.py

 # Create your views here.
+import os
+import glob
+
+from django.utils import simplejson
+from django.http import HttpResponse
+
+def templates_as_json(request):
+    json_dict = {}
+    path = os.path.join(os.path.dirname(__file__), 'templates', 'json-templates', '*.html')
+    l = glob.iglob(path)
+    for f in l:
+        json_dict[ os.path.basename(f) ] = open(f).read()
+    print json_dict
+    return HttpResponse(simplejson.dumps(json_dict, indent=4), mimetype="application/json")    

testproject/static/js/main.js

+var json_templates_blog = '';
+
 $(document).ready(function() {
-  var options = {};
-  var template = jsontemplate.Template("Hello {name}", options);
-  $("#container").html( template.expand({"name": "World"}) );
-});
+  $.getJSON('/blog/json-templates', function(data) {
+    json_templates_blog = data;
+    //alert('Templates have been loaded.');
+    $.get('/api/entry/', function(data) {
+      var options = {};
+      var template = jsontemplate.Template(json_templates_blog['index.html'], options);
+      $("#container").html( template.expand(data) );
+      //alert('Template Expanded.');
+    });
+    
+  });
+});

testproject/templates/json/index.html

+<h1>JSON-Template Blog Index</h1>
+
+{.section root}
+  <code>Cursor value is: {@}</code>
+  {.repeated section @}
+  <h2>Title: {title|html}</h2>
+  <h3>Written by: {author.first_name|html} {author.last_name|html}; {published_date}</h3>
+  <p>{content|html}</p>
+
+  <p><a href="//jayyu.com/blog/{slug|htmltag}">Permalink</a></p>
+  {.end}
+  <h2>ERROR: &ldquo;@&rdquo; not working</h2>
+{.or}
+  <h2>ERROR: &ldquo;root&rdquo; element not found</h2>
+{.end}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.