Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I added a dynamic sitemap to a blog application just recently. These steps should get you started.</p> <p>Add this route towards the bottom of your <code>config/routes.rb</code> file (more specific routes should be listed above it):</p> <pre><code>map.sitemap '/sitemap.xml', :controller =&gt; 'sitemap' </code></pre> <p>Create the <code>SitemapController</code> (app/controllers/sitemap_controller):</p> <pre><code>class SitemapController &lt; ApplicationController layout nil def index headers['Content-Type'] = 'application/xml' last_post = Post.last if stale?(:etag =&gt; last_post, :last_modified =&gt; last_post.updated_at.utc) respond_to do |format| format.xml { @posts = Post.sitemap } # sitemap is a named scope end end end end </code></pre> <p>&mdash;As you can see, this is for a blog, so is using a <code>Post</code> model.</p> <p>This is the view template (app/views/sitemap/index.xml.builder):</p> <pre><code>base_url = "http://#{request.host_with_port}" xml.instruct! :xml, :version=&gt;'1.0' xml.tag! 'urlset', 'xmlns' =&gt; 'http://www.sitemaps.org/schemas/sitemap/0.9' do for post in @posts do xml.tag! 'url' do xml.tag! 'loc', "#{base_url}#{post.permalink}" xml.tag! 'lastmod', post.last_modified xml.tag! 'changefreq', 'monthly' xml.tag! 'priority', '0.5' end end end </code></pre> <p>That's it! You can test it by bringing up <a href="http://localhost:3000/sitemap.xml" rel="nofollow noreferrer">http://localhost:3000/sitemap.xml</a> (if using Mongrel) in a browser, or perhaps by using cURL.</p> <p>Note that the controller uses the <code>stale?</code> method to issue a HTTP 304 Not Modified response if there are no new posts sinces the sitemap was last requested.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload