为pelican增加上一篇下一篇功能


功能实现很简单, pelican也有类似的插件实现 https://github.com/getpelican/pelican-plugins/tree/master/neighbors

不过自己实现起来更爽不是吗? 而且类似prev_article_in_categoryprev_article_in_subcategory的功能我并不需要

首先参考pelican的文档,基础实现

def add_neighbors(generator):
    ....

def register():
    signals.article_generator_finalized.connect(add_neighbors)

然后在generator.articles列表上进行操作,为article增加previous_articlenext_article对象

先进行排序(按时间)

articles = generator.articles
articles.sort(key=(lambda x: x.date), reverse=True)

然后可以使用iter关键字,把列表变成生成器,使用next()( python2用a.next(),python3用a.__next__())获取下一个可迭代对象

pre_article = None
articles_iter = iter(articles[1:])
for article in articles:
    next_article = next(articles_iter, None)
    setattr(article, 'previous_article', pre_article)
    setattr(article, 'next_article', next_article)
    pre_article = article

最后,在模板template中增加相关html代码,示例:

{% if article.previous_article %}
<li class="previous">
  <a href="{{ SITEURL }}/{{ article.previous_article.url }}" title="Previous article: {{ article.previous_article.title }}">
    <i class="fa fa-chevron-left"></i>
    {{ article.previous_article.title }}
  </a>
</li>
{% endif %}
{% if article.next_article %}
<li class="next">
  <a href="{{ SITEURL }}/{{ article.next_article.url }}" title="Next article: {{ article.previous_article.title }}">
    {{ article.next_article.title }}
    <i class="fa fa-chevron-right"></i>
  </a>
</li>
{% endif %}

ok,就这样

作者: honmaple
链接: https://honmaple.me/articles/2017/10/为pelican增加上一篇下一篇功能.html
版权: CC BY-NC-SA 4.0 知识共享署名-非商业性使用-相同方式共享4.0国际许可协议
wechat
alipay

加载评论