浏览代码

Merge pull request #102 from Shaked/master

Override related_posts from post metadata
Justin Mayer 11 年之前
父节点
当前提交
17980a031f
共有 2 个文件被更改,包括 39 次插入16 次删除
  1. 8 0
      related_posts/Readme.rst
  2. 31 16
      related_posts/related_posts.py

+ 8 - 0
related_posts/Readme.rst

@@ -17,3 +17,11 @@ For example::
         {% endfor %}
         </ul>
     {% endif %}
+
+
+You can also override related posts by using it as part of your post's meta data 'related_posts:'.
+The 'related_posts:' meta data works together with your existing slugs:
+
+    related_posts: slug1,slug2,slug3...slugN 
+
+N represents the RELATED_POSTS_MAX

+ 31 - 16
related_posts/related_posts.py

@@ -13,23 +13,38 @@ def add_related_posts(generator):
     # get the max number of entries from settings
     # or fall back to default (5)
     numentries = generator.settings.get('RELATED_POSTS_MAX', 5)
-
     for article in generator.articles:
-        # no tag, no relation
-        if not hasattr(article, 'tags'):
-            continue
-
-        # score = number of common tags
-        scores = Counter()
-        for tag in article.tags:
-            scores += Counter(generator.tags[tag])
-
-        # remove itself
-        scores.pop(article)
-
-        article.related_posts = [other for other, count 
-            in scores.most_common(numentries)]
-
+        # set priority in case of forced related posts
+        if hasattr(article,'related_posts'):
+            # split slugs 
+            related_posts = article.related_posts.split(',')
+            posts = [] 
+            # get related articles
+            for slug in related_posts:
+                i = 0
+                for a in generator.articles:
+                    if i >= numentries: # break in case there are max related psots
+                        break
+                    if a.slug == slug:
+                        posts.append(a)
+                        i += 1
+
+            article.related_posts = posts
+        else:
+            # no tag, no relation
+            if not hasattr(article, 'tags'):
+                continue
+
+            # score = number of common tags
+            scores = Counter()
+            for tag in article.tags:
+                scores += Counter(generator.tags[tag])
+
+            # remove itself
+            scores.pop(article)
+
+            article.related_posts = [other for other, count 
+                in scores.most_common(numentries)]
 
 def register():
     signals.article_generator_finalized.connect(add_related_posts)