changeset 593:2713b54b5d76

admin: Add summary of page in source listing.
author Ludovic Chabant <ludovic@chabant.com>
date Tue, 19 Jan 2016 21:33:31 -0800
parents 9428bd0025eb
children 8f9cf1bcbe76
files foodtruck/templates/list_source.html foodtruck/textutil.py foodtruck/views/sources.py
diffstat 3 files changed, 48 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/foodtruck/templates/list_source.html	Sun Jan 17 23:09:32 2016 -0800
+++ b/foodtruck/templates/list_source.html	Tue Jan 19 21:33:31 2016 -0800
@@ -5,7 +5,10 @@
     <div class="row">
         <div class="col-xs-12">
             {% for p in pages %}
-            <div><a href="{{p.url}}">{{p.title}}</a></div>
+            <div>
+                <h3><a href="{{p.url}}">{{p.title}}</a></h3>
+                <p>{{p.text}}</p>
+            </div>
             {% endfor %}
         </div>
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/foodtruck/textutil.py	Tue Jan 19 21:33:31 2016 -0800
@@ -0,0 +1,41 @@
+from html.parser import HTMLParser
+
+
+def text_preview(txt, length=100, *, max_length=None, offset=0):
+    max_length = max_length or (length + 50)
+    extract = txt[offset:offset + length]
+    if len(txt) > offset + length:
+        for i in range(offset + length,
+                       min(offset + max_length, len(txt))):
+            c = txt[i]
+            if c not in [' ', '\t', '\r', '\n']:
+                extract += c
+            else:
+                extract += '...'
+                break
+    return extract
+
+
+class MLStripper(HTMLParser):
+    def __init__(self):
+        super(MLStripper, self).__init__()
+        self.reset()
+        self.strict = False
+        self.convert_charrefs = True
+        self.fed = []
+
+    def handle_data(self, d):
+        self.fed.append(d)
+
+    def handle_entityref(self, name):
+        self.fed.append('&%s;' % name)
+
+    def get_data(self):
+        return ''.join(self.fed)
+
+
+def html_to_text(html):
+    s = MLStripper()
+    s.feed(html)
+    return s.get_data()
+
--- a/foodtruck/views/sources.py	Sun Jan 17 23:09:32 2016 -0800
+++ b/foodtruck/views/sources.py	Tue Jan 19 21:33:31 2016 -0800
@@ -1,6 +1,7 @@
 from flask import g, abort, render_template, url_for
 from flask.ext.login import login_required
 from piecrust.data.paginator import Paginator
+from ..textutil import text_preview, html_to_text
 from ..views import with_menu_context
 from ..web import app
 
@@ -23,7 +24,8 @@
                 'title': p['title'],
                 'slug': p['slug'],
                 'source': source_name,
-                'url': url_for('edit_page', slug=p['slug'])}
+                'url': url_for('edit_page', slug=p['slug']),
+                'text': text_preview(html_to_text(p['content']), length=300)}
         data['pages'].append(page_data)
 
     prev_page_url = None