Programmatically Creating a Sitemap for Your Middleman Website

In a previous post I explained the benefits of static websites and how cool Middleman is. In this post I will explain you how to programmatically create a sitemap for your Middleman website.

Middleman has a handy helper method named sitemap which returns an array of Resource items which are all the pages (including dynamic pages) and assets (JavaScript, CSS and images) that your website contains.

With that method, and a couple of extra snippets we will make Middleman to automatically create a sitemap.xml file during the $> middleman build task.

First of all, ensure you have the builder gem installed. You can either install it through the $> gem install command or by adding it to your Gemfile. I recommend the latter.

gem "builder"

Then, require the library in the config.rb file.

require "builder"

Next, create a sitemap.xml.builder file in the source directory of your project with the following code:

xml.instruct!
xml.urlset 'xmlns' => "http://www.sitemaps.org/schemas/sitemap/0.9" do
  sitemap.resources.select { |page| page.path =~ /\.html/ && !page.data.noindex == true }.each do |page|
    xml.url do
      xml.loc "http://www.WEBSITE#{page.url}"
      xml.lastmod Date.today.to_time.iso8601
      xml.changefreq page.data.changefreq || "monthly"
      xml.priority page.data.priority || "0.5"
    end
  end
end

IMPORTANT: If you are NOT using directory indexes you should use page.path instead of page.url in the xml.loc element.

The third line iterates over all the sitemap resources and selects only the HTML files, excluding JavaScript and CSS files, as they should not be part of the sitemap.xml file. For each page, it creates an entry in the sitemap.xml file.

You can override the default changefreq and priority values (“monthly” and 0.5 respectively) by adding the corresponding local YAML data to the page.

For example:

---
changefreq: "weekly"
priority: 1
---

Add the following line for Middleman not to wrap the sitemap into the layout.

page "/sitemap.xml", layout: false

Finally, run the $> middleman build command and check the resulting sitemap.xml file.

Hope you find it useful and see you in the next post.

ruby

Comments

comments powered by Disqus