Commits

Fredrik Håård committed e6821a8

genshi progress

Comments (0)

Files changed (2)

 from ConfigParser import SafeConfigParser, NoSectionError, NoOptionError
 import codecs
 import argparse
-from string import Template
 from genshi.template import TemplateLoader
 from genshi.core import Markup
 
     year, month, day, extra = entry.split('-')
     t = int(mktime(datetime(int(year), int(month), int(day)).timetuple()))
     return {'created': t, 'modified': t}
-
-def format_timestamp(ts, template, dt_format):
-    dt = datetime.fromtimestamp(ts)
-    return dt.strftime(dt_format)
     
-def get_timestamp(created, modified, created_tpl, modified_tpl, dt_format):
+def get_timestamps(created, modified, dt_format):
     """Return string representing timestamp in post"""
     created_dt = datetime.fromtimestamp(created)
     modified_dt = datetime.fromtimestamp(modified)
-
-    result = created_tpl.substitute(timestamp=created_dt.strftime(dt_format))
+    created = created_dt.strftime(dt_format)
+    
     #Add modification date if last change is more than 10 minutes after creation
     if modified_dt - created_dt > timedelta(minutes=10):
-        result += modified_tpl.substitute(
-            timestamp=modified_dt.strftime(dt_format))
-    return result
+        modified = modified_dt.strftime(dt_format)
+    else:
+        modified = None
+    return created, modified
 
-class Templates(object):
-    def __init__(self, templates_path):
-        self.templates_path = templates_path
-
-    def get(self, name):
-        f = open(os.path.join(self.templates_path, name), 'r')
-        result = Template(f.read().decode('utf-8'))
-        f.close()
-        return result
-
-def substitute_if_set(template, **kwargs):
-    """If any keyword argument is non-false, pass kwargs
-    to template.substiutute and return the result, otherwise
-    return the empty string"""
-    if not reduce(lambda x,y: x or y, kwargs.values()): return ""
-    return template.substitute(kwargs)
 
 def get_custom(path, name):
     source = os.path.join(path, "%s.html" % (name,))
     else:
         return None
 
+class Article(object): 
+    def __init__(self, full=True):
+        self.short_comment = not full
+        self.long_comment = full
+
+
 def generate_blaag(config_path, test_mode=False):
     """Generate html from blaag entries."""
     config = get_configuration(config_path)
 
-    templates_path = os.path.join(os.path.dirname(__file__), 'templates')
-    templates = Templates(templates_path)
     loader = TemplateLoader(
         os.path.join(os.path.dirname(__file__), 'templates'),
         auto_reload=True
         )
 
-    page_tpl = templates.get('pagetemplate.html')
-    blaag_tpl = templates.get('blaag_template.html')
-    comments_full_tpl = templates.get('comments_full.html')
-    comments_short_tpl = templates.get('comments_short.html')
-    menu_link_tpl = templates.get('menu_link.html')
-    timestamp_tpl = templates.get('timestamp.html')
-    created_tpl = templates.get('created.html')
-    modified_tpl = templates.get('modified.html')
-    disqus_tpl = templates.get('disqus.html')
-    google_analytics_tpl = templates.get('google_analytics.html')
-    footer_tpl = templates.get('footer.html')
 
     html_path = config.get('html', 'html_path')
 
     #Get timestamps from Mercurial
     datetime_format = config.get('datetime', 'datetime_format')
     for parts in data:
-        timestamp = timestamp_tpl.substitute(
-            timestamps=get_timestamp(parts['created'], parts['modified'],
-                                     created_tpl, modified_tpl, datetime_format))
+        
+        created, modified = get_timestamps(parts['created'], 
+                                            parts['modified'],
+                                            datetime_format)
         parts.update({
-                'timestamp': timestamp,
+                'created_str': created,
+                'modified_str': modified,
                 'identifier': identifier(parts)
                 })
     #Sort by creation date
     data.sort(cmp=lambda x, y: y['created']-x['created'])
-    #Create links
-    links = "\n".join([
-            menu_link_tpl.substitute(
-                link=get_absolute_url(parts), 
-                title=parts['title']) 
-            for parts in data])
 
     title = config.get('content', 'title')
 
-    disqus_name = config.get('disqus', 'name')
-    disqus = substitute_if_set(disqus_tpl, 
-                               disqus_name=disqus_name)
+    disqus = config.get('disqus', 'name')
+    google_analytics =  config.get('google_analytics', 'account')
 
-    google_analytics = substitute_if_set(google_analytics_tpl,
-                                         google_analytics_account = 
-                                         config.get('google_analytics', 'account'))
-
-    footer = substitute_if_set(footer_tpl, 
-                               footer_contents=get_custom(
-                                   config.get('content','custom_path'), 
-                                              'footer'))
+    footer = get_custom(
+        config.get('content','custom_path'), 'footer')
 
     defaults = {
         'disqus': disqus,
         'blaag_title': title,
         'author': config.get('content', 'author'),
         'google_analytics': google_analytics,
+        'footer': Markup(footer),
         }
 
+
+    articles = []
+    for parts in data:
+        article = Article(full=False)
+        article.article_id = identifier(parts)
+        article.body = Markup(parts['html_body'])
+        article.timestamp = parts['created_str']
+        article.modidied = parts['modified_str']
+        article.comment_thread_link = get_absolute_url(parts)
+        article.article_url = get_absolute_url(parts)
+        article.article_title = parts['title']
+        articles.append(article)
+
+    template = loader.load("page_template.xhtml")
+    stream = template.generate(articles = articles, **defaults)
+    content = stream.render('html', doctype='html')
+
+    #Write main page
+    with open(os.path.join(html_path, "index.html"), "w") as target:
+        target.write(content)
+
+    
     for parts in data: 
         parts.update(defaults)
         htmltitle = identifier(parts)
         if not os.path.exists(target_path):
             os.mkdir(target_path)
 
+
+
         with open(os.path.join(html_path, htmltitle, "index.html"), "w") as target:
-            #Write page for post
-            if not disqus_name:
-                fullcomments = ''
-            else:
-                fullcomments = comments_full_tpl.substitute(
-                    parts,
-                    threadid=htmltitle,
-                    disqus_name=disqus_name)
-            blaag_html = blaag_tpl.substitute(parts, comments=fullcomments)
-            target.write(page_tpl.substitute(
-                    parts,
-                    title=parts['title'], 
-                    links=links,
-                    main=blaag_html,
-                    disqus=disqus,
-                    google_analytics=google_analytics,
-                    footer=footer
-                    ).encode("utf-8"))
-            #Append post to main page
-            if not disqus_name:
-                shortcomments = ""
-            else:
-                shortcomments = comments_short_tpl.substitute(
-                    parts, 
-                    link=get_absolute_url(parts), 
-                    threadid=identifier(parts))
-            main.append(blaag_tpl.substitute(
-                    parts, 
-                    comments=shortcomments, 
-                    link=get_absolute_url(parts)))
 
-    #out = page_tpl.substitute(
-    #            defaults,
-    #            links=links, 
-    #            footer=footer,
-    #            main="\n".join(main))
-    template = loader.load("page_template.xhtml")
-    get_custom(
-        config.get('content','custom_path'), 
-        'footer')
-    articles = []
+            article = Article(full=True)
+            article.article_id = identifier(parts)
+            article.body = Markup(parts['html_body'])
+            article.timestamp = parts['created_str']
+            article.modified = parts['modified_str']
+            article.comment_thread_link = get_absolute_url(parts)
+            article.article_url = get_absolute_url(parts)
+            article.article_title = parts['title']
+            
+            stream = template.generate(articles=[article], all_articles=articles, 
+                                       **defaults)
+            target.write(stream.render("html", doctype="html"))
 
-    class Article(object): pass
 
-    for parts in data:
-        article = Article()
-        article.article_id = identifier(parts)
-        article.body = Markup(parts['html_body'])
-        article.timestamp = parts['created']
-        article.comment_thread_link = get_absolute_url(parts)
-        article.article_url = get_absolute_url(parts)
-        article.article_title = parts['title']
-        articles.append(article)
-
-    stream = template.generate(articles = articles, footer=Markup(footer), **defaults)
-    content = stream.render('html', doctype='html')
-
-
-    #Write main page
-    with open(os.path.join(html_path, "index.html"), "w") as target:
-        target.write(content)
 
     #Write rss
     description = config.get('content', 'description')

templates/page_template.xhtml

+<!DOCTYPE html>
+<html xmlns="http://www.w3.org/1999/xhtml"
+      xmlns:py="http://genshi.edgewall.org/">
+<head>
+  <title>$page_title</title>
+  <meta charset="UTF-8" />
+  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+  <link rel="stylesheet" type="text/css" href="$css" />
+  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
+  <meta name="description" content="$page_title"/>
+  <meta name="author" content="$author" />
+</head>
+<body>
+
+    <section class="page">
+      <header class="page">
+        <h1>$blaag_title</h1>  
+      </header>  
+      
+      <span py:for="article in articles">
+        <article  id="$article.article_id" class="blog box">
+          <div class="document" id="$article.article_id">
+            $article.body
+          </div>
+          
+          <div class='timestamp'>
+            Blaag created $article.timestamp
+
+          </div>
+          
+          
+          <div py:if="article.short_comment" class='shortcomments'>
+            <a href="$article.comment_thread_link##disqus_thread" 
+               data-disqus-identifier="$article.article_id">Comments</a>
+          </div> 
+
+          <div py:if="article.long_comment" class='fullcomments'>
+            <div id="disqus_thread"></div>
+            <script type="text/javascript">
+              /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
+              var disqus_shortname = '$disqus';
+              var disqus_identifier = '$article.article_id';
+              /* * * DON'T EDIT BELOW THIS LINE * * */
+              (function(d) {
+              var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
+              dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
+              (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
+        })();
+            </script>
+            <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
+            <a href="http://disqus.com" class="dsq-brlink">blog comments powered by <span class="logo-disqus">Disqus</span></a>
+          </div>
+          
+
+        </article>
+      </span>
+      <nav class="blogs">
+        <a href='/' class='menu_link'>- index -</a>
+        <a href='/rss.xml' class='menu_link'>RSS Feed</a>
+        <h4>My recent posts</h4>
+        
+        <a py:for="article in articles" href='$article.article_url' class='menu_link'>$article.article_title</a>
+
+      </nav>
+      
+      <footer class="page">
+        <p class="fineprint">$footer</p>
+      </footer>
+
+    </section>
+    
+    <!-- Add JavaScript after this point, it makes the page load faster when client does not need to interpret JS at start -->
+    <script type="text/javascript">
+      var _gaq = _gaq || [];
+      _gaq.push(['_setAccount', '$google_analytics']);
+      _gaq.push(['_trackPageview']);
+      (function() {
+        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
+        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
+        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
+      })();
+    </script>
+
+    <script type="text/javascript">
+      var  disqus_shortname = '$disqus'; 
+      (function () {
+        var s = document.createElement('script'); s.async = true;
+        s.type = 'text/javascript';
+        s.src = 'http://' + disqus_shortname + '.disqus.com/count.js';
+        (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
+      }());
+    </script>
+
+</body>
+</html>