The search object

The search object has the following attributes:

search.performed

Returns true if an HTML form with the attribute action="/search" was submitted successfully. This allows you to show content based on whether a search was performed or not.

{% if search.performed %}
    <!-- Show search results -->
{% endif %}

search.results

Returns an array of matching search result items. The items in the array can be a(n):

You can access the attributes of individual search results by looping search.results.

{% for item in search.results %}
  <h3>{{ item.title | link_to: item.url }}</h3>
{% endfor %}

Search result object_type

Search results have an additional attribute titled object_type which returns the type of each result. This is useful for writing the logic of your search results loop.

Example

{% for item in search.results %}
  <h3>{{ item.title | link_to: item.url }}</h3>
  {% if item.object_type == 'article' %}
    {% comment %}
      'item' is an article
      All article object properties can be accessed.
    {% endcomment %}

    {% if item.image %}
      <div class="result-image">
        <a href="{{ item.url }}" title="{{ item.title | escape }}">
          {{ item | image_url: 'small' | img_tag: item.title }}
        </a>
      </div>
    {% endif %}

  {% elsif item.object_type == 'page' %}
    {% comment %}
      'item' is a page.
      All page object properties can be accessed.
    {% endcomment %}

  {% else %}
    {% comment %}
      'item' is a product.
      All product object properties can be accessed.
    {% endcomment %}

    {% if item.featured_image %}
      <div class="result-image">
        <a href="{{ item.url }}" title="{{ item.title | escape }}">
          {{ item.featured_image | img_url: 'small' | img_tag: item.featured_image.alt }}
        </a>
      </div>
    {% endif %}
  {% endif %}

  <span>{{ item.content | strip_html | truncatewords: 40 | highlight: search.terms }}</span>
{% endfor %}

search.results_count

Returns the number of results found.

search.terms

Returns the string that was entered in the search input box. Use the highlight filter to apply a different style to any instances in the search results that match up with search.terms.

Input

{{ item.content | highlight: search.terms }}

Output

<!-- If the search term was "Yellow" -->
<strong class="highlight">Yellow</strong> shirts are the best!

search.types

Returns an array of strings representing the types the search was performed on. The items in the array can be any combination of article, page, product.

The search types can be seen in the URL parameters of a search page. For example, storefront.com/search?type=article,product&q=* will have a search.types array containing article and product.

Want to discuss this page?

Visit the Shopify Community