hexojs / hexo

A fast, simple & powerful blog framework, powered by Node.js.
https://hexo.io
MIT License
39.45k stars 4.85k forks source link

除了首页(index)之外, 页面(page) 如何才能分页显示文章(post) #2557

Closed me10zyl closed 7 years ago

me10zyl commented 7 years ago

For question

除了首页(index)之外, 页面(page) 如何才能分页显示文章(post) /themes/blah/layout/page.swig

{% extends "../_layout.swig" %}
{% import '../_macro/post.swig' as post_template %}

{% block title %} {{ config.title }} {% endblock %}

{% block content %}
  <section id="posts" class="posts">
    {% for post in page.posts %}
      {{ post_template.render(post) }}
    {% endfor %}
  </section>

  {% include "pagination.swig" %}
{% endblock %}

上面的例子 page.posts 没有显示文章, 只有使用未分页的 site.posts 才能显示文章。

NoahDragon commented 7 years ago

Have you tried the https://github.com/hexojs/hexo-pagination ?

me10zyl commented 7 years ago

how to do with it ? Add scripts in theme directory Or?

me10zyl commented 7 years ago

solved

Thanks @NoahDragon I used generator , https://hexo.io/zh-cn/api/generator.html I create /themes/somename/scripts/essays.js and code is here:

var pagination = require('hexo-pagination');
var assign = require('object-assign');

hexo.config.essay_generator = assign({
  per_page: typeof hexo.config.per_page === 'undefined' ? 10 : hexo.config.per_page,
  order_by: '-date'
}, hexo.config.essay_generator);

hexo.extend.generator.register('essays', function(locals){
  var config = this.config;
  var posts = locals.posts.sort(config.essay_generator.order_by);
  var pn = pagination('essays', posts, {
    perPage: 10,
    layout: ['essays'],
    data: {
    __index: true  
    }
  });

  return pn;
});

/themes/somename/layout/essays.swig:

{% extends "_layout.swig" %}
{% import '_macro/post.swig' as post_template %}

{% block title %} {{ config.title }} {% endblock %}

{% block content %}
  <section id="posts" class="posts">
    {% for post in page.posts %}
      {{ post_template.render(post) }}
    {% endfor %}
  </section>

  {% include "_partial/pagination.swig" %}
{% endblock %}

When hexo run, autoload this script and generate essays/index.html. Another option is using as hexo plugin.