1. Luke Plant
  2. lukeplant_python

Commits

Luke Plant  committed 4a0ea8b

Replaced nevow.stan with Django templates

  • Participants
  • Parent commits 0e6b92c
  • Branches default

Comments (0)

Files changed (10)

File bibleverses/config.py

View file
 import readers
 import writers
 
-OUTPUTHTMLDIR = "/home/luke/httpd/lukeplant.me.uk/src/bibleverses"
+OUTPUTHTMLDIR = "/home/luke/httpd/lukeplant.me.uk/web/bibleverses"
 
 VERSEYAMLPAGENAME = 'BibleMemorisationYaml'
 TOPICYAMLPAGENAME = 'BibleMemorisationTopicYaml'
 
 AUTHOR = "luke"
 
+TEMPLATE_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "templates")
+
 # Define 'datareader' backend and 'datawriters' backends
 
 DATABASE = "/home/luke/misc/notes/db/trac.db"
 
 datawriters = {
     'wiki': writers.TracWikiWriter(DATABASE, AUTHOR),
-    'html': writers.FileWriter(OUTPUTHTMLDIR, ".ihtml")
+    'html': writers.FileWriter(OUTPUTHTMLDIR)
 }

File bibleverses/templates/base.html

View file
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<title>{{ title }}</title>
+<link rel="StyleSheet" href="style.css" type="text/css" />
+<meta name="description" content="{{ description }}" />
+<meta name="keywords" content="Bible, memorisation" />
+</head>
+<body>
+{% block title %}<h1>{{ title }}</h1>{% endblock %}
+{% block content %}{% endblock %}
+</body>
+</html>

File bibleverses/templates/scheme.html

View file
+{% extends "base.html" %}
+{% load biblescheme %}
+{% block content %}
+
+<p>{{ scheme.description }}</p>
+<ul class="verselist">
+
+{% for item in scheme.items %}
+<li>
+  <a class="biblelink" href="{{ item.verse.verse|esvlink }}">{{ item.verse.verse }}</a>
+  <ul>
+    {% for entry in item.entries %}
+     <li class="topicentry"><span class="topicheading">{{ entry.topic }}</span>
+       {% if entry.comment %} :: {{ entry.comment }}{% endif %}
+     </li>
+    {% endfor %}
+  </ul>
+  <br/>
+  <blockquote class="bible">{{ item.verse.texts.ESV }}</blockquote>
+  <br/>
+</li>
+{% endfor %}
+</ul>
+
+{% endblock %}

File bibleverses/templates/schemes.html

View file
+{% extends "base.html" %}
+{% block content %}
+<p>Index of all schemes:</p>
+<ul>
+{% for scheme in schemes %}
+<li><a href="{{ scheme.html_filename }}">{{ scheme.name }}</a><br/>
+  <p>{{ scheme.description }}</p>
+</li>
+{% endfor %}
+</ul>
+
+{% endblock %}

File bibleverses/templates/topicnode.html

View file
+<li><span class="topicheading">{{ node.name }}</span>
+{% if node.entries %}
+  <ul>
+  {% for entry in node.entries %}  
+    <li><a href="entry.verse.verse|esvlink">{{ entry.verse.verse }}</a>
+      {% if entry.comment %}
+         -- {{ entry.comment }}
+      {% endif %}
+    </li>
+  {% endfor %}
+  </ul>
+{% endif %}
+
+{% if node.nodes %}
+  <ul>
+    {% for n in node.nodes %}
+      {% with n as node %}
+        {% include topicnode_template %}
+      {% endwith %}
+    {% endfor %}
+  </ul>
+{% endif %}
+</li>

File bibleverses/templates/topics.html

View file
+{% extends "base.html" %}
+{% block content %}
+
+<ul>
+{% for node in topicnodes %}
+   {% include topicnode_template %}
+{% endfor %}
+</ul>
+
+
+{% if uncategorised %}
+<h2>Uncategorised</h2>
+<ul>
+  {% for k, entries in uncategorised.items %}
+  <li>{{ k }}:
+    <ul>
+    {% for entry in entries %}  
+    <li><a href="entry.verse.verse|esvlink">{{ entry.verse.verse }}</a>
+      {% if entry.comment %}
+         -- {{ entry.comment }}
+      {% endif %}
+    </li>
+    {% endfor %}
+    </ul>
+  </li>
+  {% endfor %}
+
+</ul>
+
+{% endif %}
+
+{% endblock %}

File bibleverses/templatetags/__init__.py

Empty file added.

File bibleverses/templatetags/biblescheme.py

View file
+import urllib2
+from django import template
+register = template.Library()
+from django.template.defaultfilters import stringfilter
+
+@stringfilter
+def esvlink(verseref):
+    return u"http://www.gnpcb.org/esv/search/?q=%s" % urllib2.quote(verseref)
+
+register.filter('esvlink', esvlink)
+

File bibleverses/update.py

View file
 #!/usr/bin/env python
 
-from nevow import tags as T
-from nevow.flat import flatten
-import urllib2
-
-from parse import get_verses, get_topic_entries, populate_topic_tree, get_topictree, get_schemes
+from parse import get_verses, get_topic_entries, populate_topic_tree, get_topictree, get_schemes, Scheme
 from build import build_schemes
 from StringIO import StringIO
-from config import TOPICSPAGENAME, SCHEMESPAGENAME, SCHEMESPAGENAMEPREFIX, datawriters
+from config import TOPICSPAGENAME, SCHEMESPAGENAME, SCHEMESPAGENAMEPREFIX, TEMPLATE_DIR, datawriters
 from writers import FileWriter
 
+from django.conf import settings
+settings.configure(TEMPLATE_DIRS=[TEMPLATE_DIR],
+                   INSTALLED_APPS=['lukeplant_me_uk.bibleverses'],
+                   TEMPLATE_DEBUG=True)
+
+from django.shortcuts import loader
+
 # All of the 'make_x_page' functions here return a dictionary containing
 # multiple formats of the data to be written.  The 'datawriters' dict
 # is used to write the data out to different backends.
 #  - If more than one version of a text is supplied, it will
 #    prefer the one that isn't ESV
 # The html format is for public consumption
-#  - It always outputs ESV and KJV
+#  - It always outputs ESV
 # For the moment, it seems easiest to have one function that generates
 # both wiki and html.
 
     print "Topics: %d" % len(get_topic_entries(verses))
     print "Schemes: %d" % len(schemes)
 
-def smart_flatten(tags):
-    # Nevow seems to convert things to UTF8
-    s = flatten(tags)
-    if not isinstance(s, unicode):
-        s = s.decode("UTF-8")
-    return s
-
 def scheme_page_name(prefix, scheme):
     return prefix + scheme.name.title().replace(" ", "")
 
 def bible_entry_wiki(entry):
     return u"bible:\"%s\" -- %s\n" % (entry.verse, entry.comment)
 
-def bible_entry_html(entry):
-    return [mk_bible_link(entry.verse.verse), " -- " , entry.comment]
-
-def mk_bible_link(verseref):
-    return T.a(class_=u"bible", href=u"http://www.gnpcb.org/esv/search/?q=%s" % urllib2.quote(verseref))[verseref]
-
 def make_topics_page(verses, topictree, extras):
     # WIKI
     wiki = StringIO()
         for e in val:
             wiki.write(u"   * %s" % bible_entry_wiki(e))
 
-    # HTML
-    html = []
-    html.extend([
-            T.h1[ u"Bible Memorisation Topics" ],
-    ])
-
-    def get_topic_node_html(node):
-        return T.li[
-                     T.span(class_="topicheading")[node.name],
-                     (node.entries 
-                       and T.ul[ 
-                                 [ T.li[ bible_entry_html(e) ]
-                                   for e in node.entries ]
-                           ]
-                       or []),
-                     (node.nodes 
-                       and T.ul[
-                                 [ get_topic_node_html(n) 
-                                   for n in node.nodes ]
-                           ]
-                       or [])
-                   ]
-                      
-    html.append(T.ul[[get_topic_node_html(n)
-                     for n in topictree.nodes]])
-
-    html.extend([
-            T.h2[ u"Uncategorised"],
-            T.ul[
-                  [ T.li[ k,
-                          T.ul[
-                                [
-                                  T.li[ bible_entry_html(e)]
-                                  for e in val
-                                ]
-                              ]
-                        ]
-                    for k, val in extras.iteritems()]
-                ]
-    ])
-
+    html = loader.render_to_string("topics.html",
+                                   {'title':  u"Bible Memorisation Topics",
+                                    'description': u"Index of topics used for Bible memorisation scheme",
+                                    'topicnodes': topictree.nodes,
+                                    'uncategorised': extras,
+                                    'topicnode_template':  "topicnode.html" # This must be dynamic for recursion to work
+                                    })
         
     return {'wiki': wiki.getvalue(),
-            'html': smart_flatten(html)}
+            'html': html}
 
 def make_scheme_page(scheme):
     wiki = StringIO()
-    html = []
-
     wiki.write(u"""
 = Bible Memorisation Scheme - %s =
 
 """ % scheme.name)
     wiki.write(scheme.description + u"\n\n")
 
-    html.extend([
-            T.h1[u" Bible Memorisation Scheme - %s" % scheme.name],
-            T.p[scheme.description]
-    ])
-
-    ul = T.ul(class_="verselist")
-    html.append(ul)
     for item in scheme.items:
-        # WIKI
         wiki.write(u"\nbible:\"%s\"\n" % item.verse.verse)
         for e in item.entries:
             wiki.write(u" * '''%s'''" % e.topic)
                 wiki.write(u" :: %s" % e.comment)
             wiki.write(u"\n")
         write_verse_text_wiki(item.verse, wiki)
-
-        # HTML
-        ul.children.append(
-            T.li(class_="verseitem")[
-                 mk_bible_link(item.verse.verse),
-                 T.ul[
-                       [T.li(class_="topicentry")[
-                           [T.span(class_="topicheading")[e.topic],
-                            (e.comment and (" :: %s" % e.comment) or "")
-                           ]                           
-                        ]
-                       for e in item.entries]
-                 ],
-                 T.br,
-                 T.div(class_=u"verse")[ 
-                       item.verse.texts['ESV'] 
-                 ],
-                 T.br
-            ]
-        )
-
     wiki.write(u"""
 
 ----
 [[AutoNav()]]
 """)
+
+    html = loader.render_to_string("scheme.html",
+                                   {'title': u"Bible Memorisation Scheme - %s" % scheme.name,
+                                    'description': u"Bible memorisation scheme",
+                                    'scheme': scheme})
+
+
     return {'wiki': wiki.getvalue(),
-            'html': smart_flatten(html)}
+            'html': html}
 
 def make_scheme_index_page(schemes, prefix):
-    # WIKI
     wiki = StringIO()
     wiki.write(u"""= Bible Memorisation Schemes =
 
 [[AutoNav()]]
 """)
 
-    # HTML
-    html = \
-    [ 
-        T.h1[u"Bible Memorisation Schemes"],
-        T.ul[
-              [T.li[T.a(href=FileWriter.make_html_filename(scheme_page_name(prefix, scheme), ".html"))
-                       [ scheme.name ],
-                    T.br,
-                    T.p[ scheme.description ]
-                   ]
-               for scheme in schemes]
-            ]
-    ]                       
+    # quick hack to get template to work nicely
+    class HtmlScheme(Scheme):
+        def html_filename(self):
+            return FileWriter.make_html_filename(scheme_page_name(prefix, self))
+    for s in schemes:
+        s.__class__ = HtmlScheme
+    # end monkey patch
+
+    html = loader.render_to_string("schemes.html", 
+                            {'title': u"Bible memorisation schemes",
+                             'description': u"Index of Bible memorisation schemes",
+                             'schemes': schemes}
+                            )
     return {'wiki': wiki.getvalue(),
-            'html': smart_flatten(html)}
+            'html': html}
 
 if __name__ == '__main__':
     write_pages()

File bibleverses/writers.py

View file
     is stripped from the front of names."""
     # Implemented as a class as 'make_html_filename' is needed
     # elsewhere
-    def __init__(self, dirname, suffix=".html"):        
+    def __init__(self, dirname):
         self.dirname = dirname
-        self.suffix = suffix
 
     filenamestem = 'BibleMemorisation'
     @staticmethod
-    def make_html_filename(pagename, suffix):
+    def make_html_filename(pagename):
         stem = FileWriter.filenamestem
         assert pagename.startswith(stem)
         # we deliberately leave "/" in, allowing for subdirectories.
         # This will fail if dirs do not exist already
-        return pagename[len(stem):].lower() + suffix
+        return pagename[len(stem):].lower() + ".html"
 
     def __call__(self, name, data):
-        filename = self.make_html_filename(name, self.suffix)
+        filename = self.make_html_filename(name)
         with file(os.path.join(self.dirname, filename), "w") as f:
             f.write(data.encode("UTF-8"))