Make the link_to helper to fail gracefully the if the page doesn't exist

The link_to helper is sitemap aware, and according to the documentation, it can determine if the URL you provide is in the sitemap:

Middleman enhances the link_to helper to be aware of the sitemap. If
you refer to pages in your source folder (with their file extension
minus all the template extensions) then link_to will generate the
correct link…

…If the link_to helper fails to determine which page
the URL provided belongs to, it will use the URL without modifying it.

I’d like to create a link_to which points to index.html, but if there isn’t an index.html, there is no link generated at all (rather than the default behavior where a broken link is generated). Any ideas?

Check out the source to link_to (in default_helpers.rb) - it should be pretty straightforward.

Thanks! That put me on the right path.

I ended up creating a helper that wraps the link_to method and checks the sitemap before passing the arguments through. It works well enough for my use-case… here it is in case anybody is trying to do something similar:

  def link_to_if_exists(*args, &block)
    url = args[0]

    resource = sitemap.find_resource_by_destination_path(url)
    if resource.nil?
      block.call
    else
      link_to(*args, &block)
    end
  end