ruby - Jekyll - 生成 JSON 文件和 HTML 文件

标签 ruby json api jekyll

我想让 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
# jezenthomas@gmail.com
# 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

关于ruby - Jekyll - 生成 JSON 文件和 HTML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14759827/

相关文章:

javascript - 用 rails 配置 Angular 材

ruby-on-rails - Rails 从两个 Controller 调用相同的操作代码(有一点不同)

ruby-on-rails - 来自 Rails Heroku 的 Facebook Open Graph

c# - 为 WCF REST 服务生成示例数据?

javascript - API ASP.NET 和 Jquery 中 url 参数后面的数字

api - 如何通过互联网以编程方式将名片消息发送到手机

javascript - OpenAI Api 的输出延迟且随机

ruby - 在 Ruby 中构建长字符串的简洁方法

javascript - JSON.stringify lodash 合并对象的结果时出现 IE11 错误

javascript - php/ajax JSON 响应在解析后返回 [object, Object]