美文网首页Hexo
hexo-generator-index 源码分析

hexo-generator-index 源码分析

作者: 这是我用来记录技术的一个博客 | 来源:发表于2019-01-10 15:20 被阅读1次

相关文章 请按顺序阅读
hexo-pagination函数释义
hexo-generator-index 源码分析
hexo-generator-tag 源码分析

源码地址

前言:
hexo-generator-index是hexo插件中应该是最简单的一个插件了

官方hexo自3.0以后就自带此插件了
但是官方的doc文档源码中,是未用此插件的
\color{red}{如果没有用此插件,那么所有的页面都是默认用post模板,包括index页面}
post模板只能显示post页面变量
而下列变量一概没有

page.per_page   每页显示的文章数量
page.total  总页数
page.current    目前页数
page.current_url    目前分页的网址
page.posts  本页文章
page.prev   上一页的页数。如果此页是第一页的话则为 0。
page.prev_link  上一页的网址。如果此页是第一页的话则为 ''。
page.next   下一页的页数。如果此页是最后一页的话则为 0。
page.next_link  下一页的网址。如果此页是最后一页的话则为 ''。
page.path   当前页面的路径(不含根目录)。我们通常在主题中使用 url_for(page.path)。

以上变量只有在index页面才有

而hexo-generator-index解决的问题就是把以上变量带入到模板中 形成index页面

'use strict';

const pagination = require('hexo-pagination');

module.exports = function(locals) {
  const config = this.config;
  const posts = locals.posts.sort(config.index_generator.order_by); //所有文章
  const paginationDir = config.pagination_dir || 'page';//pagination_dir: page #分页文件夹名称
  const path = config.index_generator.path || ''; //路径 缺省为空 

  return pagination(path, posts, {
    perPage: config.index_generator.per_page, //找的是 _config.yml里面index_generator的per_page
    layout: ['index', 'archive'],
    format: paginationDir + '/%d/',
    data: {
      __index: true
    }
  });
};
  1. 首先要了解hexo-pagination这个内部工具
    pagination(base, posts, [options])
    地址在这里
    2 通过这个函数 我们知道我们可以用的变量为
    this.config:_config.yml里面所有的值
    locals:包含下列值
变量 描述
posts 所有文章
pages 所有分页
categories 所有分类
tags 所有标签

3 调用方式为:


image.png

其实都是pagination的返回值而已

4 通过这个插件我们可以学到:
它仅仅指定了分页对象需要打到哪个路径上,然后通过page变量调取

举例:
一共创建4篇文章
修改config,每页3篇文章 这样就有了两页
在index.ejs中,写如下代码

 current:<%= page.current %><br />
 <% page.posts.each(function(post){ %>
    <%= post.title %>
  <% }) %><br />
 current-url:<%= page.current_url %>
 total: <%= page.total %><br />
 next: <%= page.next %><br />
 next_link: <%= page.next_link %><br />
 pre: <%= page.pre %><br />
 pre_link: <%= page.pre_link %><br />
 __index: <%= page.__index %><br />
 per_page: <%= page.per_page %><br />
 path: <%= page.path %><br />

在前端显示如下:
http://localhost:4000/

current:1
hh gg asdf 
current-url: total: 2
next: 2
next_link: page/2/
pre: 
pre_link: 
__index: true
per_page: 
path: index.html

http://localhost:4000/page/2/

current:2
Hello World 
current-url:page/2/ total: 2
next: 0
next_link: 
pre: 
pre_link: 
__index: true
per_page: 
path: page/2/index.html

相关文章

网友评论

    本文标题:hexo-generator-index 源码分析

    本文链接:https://www.haomeiwen.com/subject/oegorqtx.html