middlemanmiddleman-4

In middleman, how can I get a root-path url that includes my `http_prefix` value?


I've run into this stumper with my Middleman site, when I use http_prefix and try to get my footer to produce the same link paths from different page-level urls.

Info about my site

I have a site where I must use http_prefix.

For the context of this question, let's say the root url is:

foo.example.com/my-site

thus http_prefix is set to my-site.

I have a partial for the page footer which is included on every page.

The problem

I have a footer, defined in a partial, that appears on every page. The link_to helper behaves differently depending on whether the page is in the root path or a deeper path.

For example, let's say the footer calls link_to('Privacy Policy', 'privacy-policy').

If I add a slash to make it absolute path i.e. link_to('Privacy Policy', '/privacy-policy'), I get this on both pages:

The absolute path makes it ignore http_prefix. That's certainly not what I want!

How can I use link_to in a way that gets me the same root-dir location no matter which page it's called from?


Solution

  • I created this helper to deal with it. Feels like a hack.

    helpers do
      def root_url(relative_to_root)
        if relative_to_root[0]=='/'
          relative_to_root = relative_to_root[1..-1]
        end
        "#{config.http_prefix}#{relative_to_root}"
      end
    end
    

    Now I can call this:

    =link_to 'About', root_url('about.html')
    

    This link will always give a link relative to root, including http_prefix, no matter what page this link appears on.

    The more that I think about this, the more I think that link_to is simply deficient when it comes to http_prefix. It's a bug! I think the actual fix needed in Middleman is to make link_to prepend http_prefix to links that start with /.