Generating files by programming in Jekyll

老子叫甜甜 提交于 2019-12-08 12:35:40

问题


Suppose I have some data in the _data folder from which I want to automatically generate pages. That is: imagine _data/structure.md is something as follows

chapters:
  -
    chapter1  
    chapter2 
    chapter3 
    ...

and I need static files chapter1.md, chapter2.md ... and so on which are quite similar in structure (for instance, chapter1.md is

---
title:chapter1
layout: default
---

This is chapter1!!

). Is there a way to create these files automatically, without doing them by hand, just changing or adding items in the _data file?


回答1:


You can use a generator (documentation). This can be something like this :

module Jekyll

  class DataPage < Page
    def initialize(site, base, dir, name)
      @site = site
      @base = base
      @dir = dir
      @name = name
      self.process(@name)
      self.data ||= {}
      self.data['layout'] = 'default'
      self.data['title'] = data
    end
  end

  class CategoryPageGenerator < Generator
    def generate(site)
      datas = site.data['structure']
      datas.each do |data|
        name = "#{data}.md"
        page = Jekyll::DataPage.new(site, site.source, @dir, name)
        page.data['title'] = data
        page.data['layout'] = 'default'
        page.content = "This is #{data}"
        site.pages << page
      end
    end
  end

end


来源:https://stackoverflow.com/questions/37207189/generating-files-by-programming-in-jekyll

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!