【问题标题】:Use a custom helper in Middleman Frontmatter在 Middleman Frontmatter 中使用自定义助手
【发布时间】:2014-12-31 01:28:08
【问题描述】:

我的中间人结构如下所示:

source/
  blog/
    post-one.md
    post-two.md
  blog.erb
  index.md

我的config.rb 定义了这个助手:

helpers do
  TOP_LEVEL_DIR = Dir.pwd

  def posts
    files = Dir["#{TOP_LEVEL_DIR}/source/blog/*"]

    files.map do |file|
      created_at = `git log --follow --date=short --pretty=format:%ad --diff-filter=A -- #{file}`
      basename = File.basename(file).split('.')[0]

      {
        date: created_at,
        link: '/blog/' + basename,
        title: basename.gsub('-', ' ').capitalize
      }
    end
  end
end

而我的blog.erb 看起来像这样:

<ul>
  <% posts.each do |post| %>
    <li><%=post[:date]%>: <%= link_to post[:title], post[:link] %></li>
  <% end %>
</ul>

这对我来说非常有效,但我缺少一件事。我想在post-onepost-two 的布局中显示我在自定义助手中定义的created_at 元数据。

通常这是通过定义 Frontmatter 来完成的,但我不想手动输入每个帖子在 git 中可用的日期。

所以我需要一种方法来定义一个允许我访问current_page 元数据的自定义助手。或者以其他方式将我在 posts 助手中手动创建的元数据传递到布局中。

【问题讨论】:

    标签: middleman


    【解决方案1】:

    这比我想象的要简单得多。 current_page 在助手中可用,所以我可以像这样在 config.rb 中的助手中直接使用它:

    helpers do
      def created_at
        # `git log --follow --date=short --pretty=format:%ad --diff-filter=A -- #{current_page.source_file}`
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-17
      • 2015-10-24
      • 2021-01-26
      • 1970-01-01
      • 2018-08-10
      • 2019-11-07
      • 2016-01-29
      • 2013-06-27
      相关资源
      最近更新 更多