ruby – Jekyll – 在HTML文件旁边生成JSON文件

我想让Jekyll为每个页面和帖子创建一个HTML文件和一个JSON文件.这是为了提供我的Jekyll博客的JSON API – 例如可以在/posts/2012/01/01/my-post.html或/posts/2012/01/01/my-post.json访问帖子

有谁知道是否有一个Jekyll插件,或者我将如何开始编写这样的插件,并排生成两组文件?

解决方法

我也在寻找类似的东西,所以我学到了一些ruby并制作了一个脚本,可以生成Jekyll博客文章的JSON表示.我还在努力,但大部分都在那里.

我把它和Gruntjs,Sass,Backbonejs,Requirejs和Coffeescript放在一起.如果你愿意,你可以看看my jekyll-backbone project on Github.

# encoding: utf-8
#
# Title:
# ======
# Jekyll to JSON Generator
#
# Description:
# ============
# A plugin for generating JSON representations of your
# site content for easy use with JS MVC frameworks like Backbone.
#
# Author:
# ======
# Jezen Thomas
# [email protected]
# http://jezenthomas.com

module Jekyll
  require 'json'

  class JSONGenerator < Generator
    safe true
    priority :low

    def generate(site)
      # Converter for .md > .html
      converter = site.getConverterImpl(Jekyll::Converters::Markdown)

      # Iterate over all posts
      site.posts.each do |post|

        # Encode the HTML to JSON
        hash = { "content" => converter.convert(post.content)}
        title = post.title.downcase.tr(' ','-').delete("’!")

        # Start building the path
        path = "_site/dist/"

        # Add categories to path if they exist
        if (post.data['categories'].class == String)
          path << post.data['categories'].tr(' ','/')
        elsif (post.data['categories'].class == Array)
          path <<  post.data['categories'].join('/')
        end

        # Add the sanitized post title to complete the path
        path << "/#{title}"

        # Create the directories from the path
        FileUtils.mkpath(path) unless File.exists?(path)

        # Create the JSON file and inject the data
        f = File.new("#{path}/raw.json","w+")
        f.puts JSON.generate(hash)
      end

    end

  end

end

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...