Commits

Anonymous committed 37d3763

Start of Front end. I think project is ready for 'Start of ending' phase...

  • Participants
  • Parent commits 0d0ba16

Comments (0)

Files changed (7)

gadmin/models/gpage.py

 from google.appengine.ext import db
+from google.appengine.api import users
 from google.appengine.ext.db import polymodel
 from gadmin.types import get_types
+from django.shortcuts import render_to_response
+from django.template import TemplateDoesNotExist
+from django.core.urlresolvers import reverse
 # TODO: check all posible 'more than 1000' cases
-# TODO: some kind of cache for GPage properties
+# TODO: profile and cache get_*
+
+def _draft_filter(func):
+    def newfunc(*args, **kwargs):
+        ret = func(*args, **kwargs)
+
+        user = users.get_current_user()
+        if user or not ret:
+            return ret
+
+        if hasattr(ret, 'draft'):
+            if ret.draft:
+                return None
+            return ret
+        elif hasattr(ret, 'filter'):
+            return ret.filter('draft =', False)
+        return [p for p in ret if not p.draft]
+    return newfunc
 
 def get_root():
     root = GPage.all().filter('level =', 0).get()
     for p in get_all():
         yield (str(p.key()), str(p))
 
+@_draft_filter
 def get_all():
     root = get_root()
     return [root,] + get_descendants(root)
 
+@_draft_filter
 def get_branch(page):
     return get_descendants(page)
 
+@_draft_filter
 def get_children(page):
     return GPage.all().filter('top =', page.key()).order('order')
 
+@_draft_filter
 def get_prev(page):
     return GPage.all() \
             .filter('top =', page.top.key()) \
             .filter('order =', page.order - 1)
 
+@_draft_filter
 def get_next(page):
     return GPage.all() \
             .filter('top =', page.top.key()) \
             .filter('order =', page.order + 1)
 
+@_draft_filter
+def get_by_slug(slug=''):
+    if slug:
+        return GPage.all().filter('slug =', slug).get()
+    return get_root()
+
+
+@_draft_filter
 def get_descendants(page, depth=-1):
     if depth == 0:
         return []
         pages += [c] + get_descendants(c, depth)
     return pages
 
+@_draft_filter
 def get_breadcrumb(page):
-    # TODO: implement
-    pass
+    tops = []
+    top = page
+    while True:
+        if not top:
+            break
+        tops.append(top)
+        top = top.top
+    return list(reversed(tops))
 
 def add_as_last_child(page, destination):
     try:
     def has_prev(self):
         return (not self.get_prev())
 
+    def get_response(self):
+        data = {
+            'current': self,
+            'breadcrumb': get_breadcrumb(self)
+        }
+        tname = 'gsite/types/%s.html' % self.class_name().lower()
+        try:
+            return render_to_response(tname, data)
+        except TemplateDoesNotExist:
+            return render_to_response('gsite/gpage.html', data)
+        return None
+
+    def get_link_target(self):
+        return None
+
+    def get_absolute_url(self):
+        return reverse('gadmin.views.site', args=[self.slug])
+
     @property
     def next(self):
         return get_next(self)
     def children(self):
         return get_children(self)
 
+    def __eq__(self, other):
+        return self.slug == other.slug
+
     def __str__(self):
         return "%s %s" % ("--" * self.level, self.title)
 

gadmin/templatetags/gsite.py

+from django import template
+from django.template import TemplateSyntaxError
+from gadmin.models import gpage
+
+register = template.Library()
+
+class ListMenuNode(template.Node):
+    def __init__(self, item, depth):
+        self.item = template.Variable(item)
+        self.depth = int(depth)
+
+    def render(self, context):
+        item = self.item.resolve(context)
+        current = template.Variable('current').resolve(context)
+        breadcrumb = template.Variable('breadcrumb').resolve(context)
+        lis = []
+        try:
+            items = gpage.get_descendants(item, self.depth)
+        except AttributeError:
+            item = gpage.get_by_slug(str(item))
+            if not item:
+                return ''
+            items = gpage.get_descendants(item, self.depth)
+        if not items:
+            return ''
+        return self.output(items, current, breadcrumb)
+
+    def output(self, items, current, breadcrumb):
+        level = items[0].level
+        out = []
+        for p in items:
+            if level < p.level:
+                out.append('<ul>')
+            if level > p.level:
+                out.append('</ul>')
+
+            cl = ''
+            if p == current:
+                cl = ' class="current"'
+            elif p in breadcrumb:
+                cl = ' class="branch"'
+            out.append('<li%s>' % (cl))
+
+            target = ''
+            if p.get_link_target():
+                target = ' target="%s"' % p.get_link_target()
+            params = (p.get_absolute_url(), target, p.menu_title)
+            out.append('<a href="%s"%s>%s</a>' % params)
+            level = p.level
+        return ''.join(out)
+
+def list_menu(parser, token):
+    args = token.split_contents()
+    if len(args) >= 3:
+        tag_name, item, depth = args[0], args[1], args[2]
+    elif len(args) == 2:
+        tag_name, item = args[0], args[1]
+        depth = 1
+    else:
+        tag_name = args[0]
+        raise TemplateSyntaxError(
+                '%r tag requires at least single param' \
+                % tag_name)
+    return ListMenuNode(item, depth)
+register.tag('gsite_list_menu', list_menu)
+
+class GetPageNode(template.Node):
+    def __init__(self, slug, var_name):
+        self.slug = template.Variable(slug)
+        self.var_name = var_name
+
+    def render(self, context):
+        slug = self.slug.resolve(context)
+        context[self.var_name] = gpage.get_by_slug(str(slug))
+        return ''
+
+def get_page(parser, token):
+    args = token.split_contents()
+    if len(args) != 4 and args[2] != 'as':
+        raise TemplateSyntaxError("%r tag must be {% %s 'page-slug' as var_name %}" % \
+                (args[0], args[0]))
+    return GetPageNode(args[1], args[3])
+register.tag('gsite_get_page', get_page)
+
 from gadmin import types
-types.load() # Preloads all gpage.GPage sublclasses
+types.load() # Preloads all gpage.GPage subclasses
 
 from django.http import Http404, HttpResponse
 from django.shortcuts import render_to_response, redirect
         return response
     return HttpResponse("{}")
 
+def site(request, slug=""):
+    page = gpage.get_by_slug(slug)
+    if not page:
+        raise Http404()
+    return page.get_response()
+
 from google.appengine.ext import db
 from gadmin.types import register
 from gadmin.forms import PicasaWidget
+from django.http import HttpResponseRedirect
 from django import forms
 
 class Menu(GPage):
 class Link(GPage):
     url = db.StringProperty()
     target = db.StringProperty(choices=['_self', '_blank'])
+
+    def get_link_target(self):
+        return self.target
+
+    def get_response(self):
+        return HttpResponseRedirect(self.url)
 register.add(Link)
 

templates/gsite/base.html

+<html>
+<head>
+  <meta http-equiv="content-type" content="text/html; charset=utf-8">
+  <title>{{ current.title }}</title>
+  <style>
+    ul li.branch  a{
+      color: #f00;
+    }
+    ul li.current  a{
+      color: #0f0;
+    }
+  </style>
+</head>
+<body>
+  <div id="Content">
+    {% block content %}
+    {% endblock %}
+  </div>
+</body>
+</html>

templates/gsite/gpage.html

+{% extends "gsite/base.html" %}
+{% load gsite %}
+{% block content %}
+  {% gsite_get_page "secret" as secret_page %}
+  {% if secret_page %}
+    <a href="{{ secret_page.get_absolute_url }}">{{ secret_page.menu_title }}</a>
+    <br/>
+    <br/>
+  {% endif %}
+  {% for page in breadcrumb|slice:"2:" %}
+    {{ page.menu_title }} -&gt;
+  {% endfor %}
+  <ul>{% gsite_list_menu 'top-menu' 3 %}</ul>
+  {{ current.content|safe }}
+  <img src="{{ current.picture }}" alt="Picture" />
+{% endblock %}
 
 urlpatterns = patterns('',
     (r'^gadmin/', include('gadmin.urls', namespace='gadmin')),
+    (r'^site/(.*)$', 'gadmin.views.site')
 )