Best way to create/concatenate absolute URLs?

In the docs I sometimes see this pattern to create URLs:
{{ page.url | prepend: site.url }}

To me this pattern is easier to read and has the same result:
{{ site.url }}{{ page.url }}

Of course this would also be an option:
{{ site.url | append: page.url }}

Do you know any reasons to prefer one over the other? Does the choice affect performance?

The best option is to use the builtin URLFilters:

  • if you want to prefix site.url, use absolute_url filter:
    {{ page.url | absolute_url }}
    
  • If you don’t want to prefix site.url, use relative_url filter:
    {{ page.url | relative_url }}
    

The benefits are that the url filters are smart about handling site.baseurl and site.url

2 Likes

Thanks, ashmaroli! Didn’t expect that and I’m definitely going to use it. That said, I’m still wondering about the concatenation options in general.

Performance-wise, you wouldn’t be able to tell unless the site has thousands and higher of such constructs.
So it boils down to ease of use, readability, etc. {{ site.url }}{{ page.url }} is fine if all those curly braces don’t bother you. If it looks ugly, swap with
{{ page.url | prepend: site.url }}

And if you’re authoring a theme that would be used by others, you can’t really guarantee that those users would not have a slash at the end of site.url or site.baseurl because then the result would be an incorrect URI like http://example.com//blog//about.html. That’s where the URLFilters come in handy.

2 Likes