Two versions of each blog post in Jekyll

扶醉桌前 提交于 2020-01-24 11:09:03

问题


I need two versions of each of my posts in a very simple Jekyll setup: The public facing version and a barebones version with branding specifically for embedding.

I have one layout for each type:

post.html
post_embed.html

I could accomplish this just fine by making duplicates of each post file with different layouts in the front matter, but that's obviously a terrible way to do it. There must be a simpler solution, either at the level of the command line or in the front matter?

Update: This SO question covers creating JSON files for each post. I really just need a generator to loop through each post, alter one value in the YAML front matter (embed_page=True) and feed it back to the same template. So each post is rendered twice, once with embed_page true and one with it false. Still don't have a full grasp of generators.


回答1:


Here's my Jekyll plugin to accomplish this. It's probably absurdly inefficient, but I've been writing in Ruby for all of two days.

module Jekyll
  # override write and destination functions to taking optional argument for pagename
  class Post
    def destination(dest, pagename)
      # The url needs to be unescaped in order to preserve the correct filename
      path = File.join(dest, CGI.unescape(self.url))
      path = File.join(path, pagename) if template[/\.html$/].nil?
      path
    end

    def write(dest, pagename="index.html")
      path = destination(dest, pagename)
      puts path
      FileUtils.mkdir_p(File.dirname(path))
      File.open(path, 'w') do |f|
        f.write(self.output)
      end
    end
  end

  # the cleanup function was erasing our work
  class Site
    def cleanup
    end
  end

  class EmbedPostGenerator < Generator
    safe true
    priority :low
    def generate(site)
      site.posts.each do |post|
        if post.data["embeddable"]
          post.data["is_embed"] = true
          post.render(site.layouts, site.site_payload)
          post.write(site.dest, "embed.html")
          post.data["is_embed"] = false
        end
      end
    end
  end
end


来源:https://stackoverflow.com/questions/17091036/two-versions-of-each-blog-post-in-jekyll

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