jekyll-friend
jekyll-friend

Reputation: 61

Generating files by programming in Jekyll

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?

Upvotes: 1

Views: 431

Answers (1)

David Jacquel
David Jacquel

Reputation: 52789

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

Upvotes: 4

Related Questions