【问题标题】:Prevent jekyll from cleaning up generated JSON file?防止 jekyll 清理生成的 JSON 文件?
【发布时间】:2018-02-13 22:40:42
【问题描述】:

我编写了一个简单的插件,可以生成一个小的 JSON 文件

module Jekyll

  require 'pathname'
  require 'json'

  class SearchFileGenerator < Generator
     safe true

     def generate(site)
       output = [{"title" => "Test"}]

       path = Pathname.new(site.dest) + "search.json"

       FileUtils.mkdir_p(File.dirname(path))
       File.open(path, 'w') do |f|
         f.write("---\nlayout: null\n---\n")
         f.write(output.to_json)
       end
       # 1/0
     end
   end
end

但是每次 Jekyll 运行完成时,生成的 JSON 文件都会被删除。如果我取消注释除以零行并导致它出错,我可以看到 search.json 文件正在生成,但随后被删除。如何防止这种情况发生?

【问题讨论】:

    标签: json ruby jekyll


    【解决方案1】:

    我发现了以下问题,建议将文件添加到keep_fileshttps://github.com/jekyll/jekyll/issues/5162 有效:

    新代码似乎避免了search.json被删除:

    module Jekyll
    
      require 'pathname'
      require 'json'
    
      class SearchFileGenerator < Generator
         safe true
    
         def generate(site)
           output = [{"title" => "Test"}]
    
           path = Pathname.new(site.dest) + "search.json"
    
           FileUtils.mkdir_p(File.dirname(path))
           File.open(path, 'w') do |f|
             f.write("---\nlayout: null\n---\n")
             f.write(output.to_json)
           end
           site.keep_files << "search.json"
         end
       end
    end
    

    【讨论】:

      【解决方案2】:

      将您的新页面添加到site.pages

      module Jekyll
        class SearchFileGenerator < Generator
          def generate(site)
            @site  = site
            search = PageWithoutAFile.new(@site, site.source, "/", "search.json")
            search.data["layout"] = nil
            search.content = [{"title" => "Test 32"}].to_json
            @site.pages << search
          end
        end
      end
      

      灵感来自jekyll-feed code

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-23
        • 1970-01-01
        • 1970-01-01
        • 2020-12-11
        • 1970-01-01
        • 1970-01-01
        • 2015-04-01
        • 1970-01-01
        相关资源
        最近更新 更多