LoginSignup
0
1

More than 5 years have passed since last update.

Middlemanでsitemap.xmlを生成する(lastmod付き)

Last updated at Posted at 2017-02-06

Middlemanでsitemap.xmlを作りたかったので、以下の投稿を参考に作成しました。

この記事でも説明されているのですが、更新日(lastmod)を付けるための言及において、

  • ファイルの更新日時を取得する
  • Frontmatterでmodify_dateを定義しておく

という2パターンがあったのですが、ファイルの更新日時に関しては、git pullしたらファイルの更新日時がpullした時間になってしまうという問題があります。

そこで、gitで管理しているんなら、gitで管理しているファイルの更新日時を取得すればいいんじゃないか?と考えて、ちょっと改変してみました。

sitemap.xml.builder
---
layout: false
---
require 'open3'

xml.instruct!
xml.urlset 'xmlns' => 'http://www.sitemaps.org/schemas/sitemap/0.9' do
  sitemap.resources.each do |resource|
    xml.url do
      xml.loc "http://www.example.com#{resource.url}"
      output, error, status = Open3.capture3("git log --pretty=format:%ci -n1 #{resource.source_file}")
      xml.lastmod output.split(' ').first
    end if resource.destination_path =~ /\.html$/
  end
end

Open3.capture3で、コマンドを実行した結果を標準出力に出したものをキャプチャします(変数outputに)。
変数outputには2017-01-26 11:51:18 +0900のような形式でファイルの更新日時が入っているので、日付だけ取り出すようにしました。

結果は、以下のように。

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>http://www.example.com/foo/</loc>
    <lastmod>2017-01-19</lastmod>
  </url>
</urlset>

こっちのほうが楽かなと思う。
しかし、一覧ページなどの更新日時が反映されないかなという懸念点がある…。

参考URL

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1