【问题标题】:Add URL field to Jekyll post yaml data将 URL 字段添加到 Jekyll 发布 yaml 数据
【发布时间】:2014-08-16 12:35:33
【问题描述】:

我想以编程方式将单行 YAML 前端数据附加到所有 source _posts 文件。

背景:我目前有一个由 Jekyll 提供支持的网站,它使用以下插件生成其 URL:

require "Date"

module Jekyll
  class PermalinkRewriter < Generator
    safe true
    priority :low

    def generate(site)
      # Until Jekyll allows me to use :slug, I have to resort to this
      site.posts.each do |item|
        day_of_year = item.date.yday.to_s
        if item.date.yday < 10
          day_of_year = '00'+item.date.yday.to_s
        elsif item.date.yday < 100
          day_of_year = '0'+item.date.yday.to_s
        end

        item.data['permalink'] = '/archives/' + item.date.strftime('%g') + day_of_year + '-' + item.slug + '.html'
        end
      end
    end
  end
end

所有这一切都会生成一个类似/archives/12001-post-title.html 的 URL,它是两位数的年份(2012 年),然后是撰写帖子的年份 of(在本例中) ,1 月 1 日)。

(顺便说一句:我喜欢这个,因为它本质上为每个 Jekyll 帖子创建了一个 UID,然后可以在生成的 _site 文件夹中按名称排序,并按时间顺序结束)。

但是,现在我想更改我写的新帖子的 URL 方案,但我不希望这会在生成网站时破坏我所有现有的 URL。因此,我需要一种方法来遍历我的源 _posts 文件夹并将插件生成的 ULR 附加到每个帖子的 YAML 数据中,并使用 the URL: front matter

我不知道如何做到这一点。我知道如何使用 Ruby 将行附加到文本文件中,但是如何为我的所有 _posts 文件执行此操作并让该行包含插件生成的 URL?

【问题讨论】:

  • 不确定我能否回答您的问题,但如果在这里找不到好的答案,您可以随时将问题发布到github.com/jekyll/jekyll-help

标签: ruby jekyll github-pages


【解决方案1】:

等等!在 Jekyll 2.2.0 上测试

module Jekyll
  class PermalinkRewriter < Generator
    safe true
    priority :low

    def generate(site)

      @site = site
      site.posts.each do |item|
        if not item.data['permalink']

          # complete string from 1 to 999 with leading zeros (0)
          # 1 -> 001 - 20 -> 020
          day_of_year  = item.date.yday.to_s.rjust(3, '0')
          file_name    = item.date.strftime('%g') + day_of_year + '-' + item.slug + '.html'
          permalink    = '/archives/' + file_name

          item.data['permalink'] = permalink

          # get post's datas
          post_path    = item.containing_dir(@site.source, "")
          full_path    = File.join(post_path, item.name)
          file_yaml    = item.data.to_yaml
          file_content = item.content

          # rewrites the original post with the new Yaml Front Matter and content
          # writes 'in stone !'
          File.open(full_path, 'w') do |f|
            f.puts file_yaml
            f.puts '---'
            f.puts "\n\n"
            f.puts file_content
          end

          Jekyll.logger.info "Added permalink " + permalink + " to post " + item.name
        end
      end
    end
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多