Liquid How-to: Showing Canonical Content
The Problem
It is not uncommon for some of your site’s most important pages to be accessed with slightly different urls. For instance a category page might be accessed using filters or have sorting applied, both of which may add query parameters to the url, eg: ?sort=price&page=3
This may sometimes result in lower SEO rankings because the same content is being displayed on what are considered different pages because of the query parameters.
Here is a tip on how to detect what url the page was accessed with and adapting the content accordingly.
The Solution
The current_request
Global Variable
One of the global variables you can use in your liquid code is current_request.
It will return a Request object that provides some information about the how the page was accessed (requested). You can check the documentation for all the attributes it offers, but for now we are just going to use these three:
- fullpath: this returns the whole of the url after the domain, eg
/products?page=3
- path: this returns the url after the domain and up to the “?”, eg
/products
- query_string: this returns everything after “?” if there is one, eg
page=3
If your page was accessed with any query parameters you might want to show some different content. Here are a few ways to do this:
Using fullpath
{% if current_request.fullpath == "/current-offers" %}
This content will show if there the full path exactly matches "/current-offers"
This will not match: "/current-offers?sort=price"
{% else %}
This content will show in all other circumstances
{% endif %}
Using query_string
{% if current_request.query_string == "" %}
This content will show if there are no query parameters
{% else %}
This content will show if the page was requested with query parameters
{% endif %}
Using a combination of path
and query_string
This method is useful if you want to change the content based on what query parameters were used.
{% if current_request.path == "/current-offers" %}
We know we're on the Current Offers page
We don't yet know if it was accessed with query parameters
{% if current_request.query_string != "" %}
Ok so the page was accessed with query params
{% assign params = current_request.query_string | prepend: "&" %}
{% if params contains "&page=" %}
The page was accessed with the query parameter: page!
{% elsif params contains "&sort=" %}
The page was accessed with the query parameter sort!
{% else %}
The page was accessed with some other query parameters! ¯\_(ツ)_/¯
{% endif %}
{% else %}
The page was not accessed with any query parameters
{% endif %}
{% endif %}
Back to Documentation