skip to Main Content

I’m trying to get a Shopify collection page to display different .js embeds on a specific part of the page, depending on the URL of the current page.

Can this be done using {% if page.url == %} if so, how would I have variants of page URLs and specific embed codes?

The page URL looks like this:

https://www.example.com/collections/technology/technology-connected-home

The embed code looks like this:

<script type="text/javascript" src="https://apps.example.com/app/js/18218989163.js"></script>```

3

Answers


  1. Each Shopify store has different types of pages: index (aka home), product, collection, page, blog, article, and cart. Here is the full list of page types.

    So, this page.url will only work on a page object of type page for all other types you need to use the proper page object to get the url:

    • collection.url
    • product.url
    • etc…

    In your case I’d suggest using case/when, add your logic in a snippet and render it in theme.liquid.

    Here is an example:

    {% if request.page_type == 'page' %}
      {% case page.url %}
        {% when '/pages/about-us' %}
          {{ 'pages__about-us.js' | script_tag }}
        {% when '/pages/contact-us' %}
          {{ 'pages__contact-us.js' | script_tag }}
        {% else %}
          {{ 'pages__generic.js' | script_tag }}
      {% endcase %}
    {% endif %}
    

    ref

    You gonna have to check for request.page_type before creating your case/when or another approach would be to check the type at the top of the snippet, like:

    {% comment %} Set page object type {% endcomment %}
    {% case request.page_type %}
      {% when 'page' %}
        {% assign page_object = page %}
      {% when 'collection' %}
        {% assign page_object = collection %}
      {% when 'product' %}
        {% assign page_object = product %}
    {% endcase %}
    
    {% comment %} Load JS based on page URL{% endcomment %}
    {% case page_object.url %}
      {% when '/pages/about-us' %}
        {{ 'pages__about-us.js' | script_tag }}
      {% when '/pages/contact-us' %}
        {{ 'pages__contact-us.js' | script_tag }}
      {% else %}
        {{ 'pages__generic.js' | script_tag }}
    {% endcase %}
    

    This isn’t a bulletproof solution, however it should be enough for you to build on top of it.

    Good luck!

    Login or Signup to reply.
  2. I recommend using page.handle and identifying the handle. I do not believe page.url will do what you need

    Login or Signup to reply.
  3. You can also try this as handle can never be changed.

    {% case page.handle %}
        {% when 'about-us' %}
          {{ 'pages_about-us.js' | script_tag }}
        {% when 'contact-us' %}
          {{ 'pages_contact-us.js' | script_tag }}
        {% else %}
          {{ 'pages_generic.js' | script_tag }}
      {% endcase %}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search