Skip to content

Instantly share code, notes, and snippets.

@amitu
Created September 15, 2013 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitu/6572756 to your computer and use it in GitHub Desktop.
Save amitu/6572756 to your computer and use it in GitHub Desktop.
djangothis with labels
from importd import d
from path import path
from datetime import datetime
from djangothis.app import dotslash, read_yaml, watchfile
from django.shortcuts import render
posts = None
labels = {}
def get_posts():
global posts
if posts is not None: return posts
posts = []
_posts = path(dotslash("_posts"))
if not _posts.exists(): return posts
for post in _posts.walkfiles():
if post.endswith(".swp"): continue
watchfile(post)
content = post.open().read().decode("utf-8")
_, header, body = content.split(u"---", 2)
body = body.replace(u"{% include JB/setup %}", u"")
header = read_yaml(header)
y, m, d, slug = post.basename().split("-", 3)
slug = slug[:-3]
post = {
"date": datetime(int(y), int(m), int(d)),
"url": "/%s/%s/%s.html" % (y, m, slug),
"title": header["title"],
"header": header,
"body": body,
"labels": header.get("labels", []),
}
posts.append(post)
for label in post["labels"]:
labels.setdefault(label, []).append(post)
posts.sort(lambda x, y: cmp(x["date"], y["date"]), reverse=True)
for items in labels.values():
items.sort(lambda x, y: cmp(x["date"], y["date"]), reverse=True)
return posts
get_posts()
def context_processor(request):
return {
"settings": d.settings,
"posts": get_posts(),
"labels": labels,
}
def find_post_by_path(pth):
prev, curr, nex = None, None, None
for post in get_posts():
if curr:
nex = post
break
if post["url"] == pth:
curr = post
else:
prev = post
return prev, curr, nex
@d("/<int4:year>/<int2:month>/<slug:slug>.html")
def post_page(request, year, month, slug):
prev, curr, nex = find_post_by_path(request.path)
return "post.html", {
"previosu": prev,
"post": curr,
"next": nex
}
@d("/tag/<slug:label>/")
def label_page(request, label):
return render(request, "label.html", {"label": label, "posts": labels[label]})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment