COLUMNS
Implementing “Recently viewed collections” without an app
To display a list of recent viewed collections we are going to create three files. The first one will keep a list of recently visited collections in LocalStorage, the second file will be used to render the data of a collection in a presentable way, and the third one will be used to render the complete list of recently viewed collections.
1) Saving collection handles in LocalStorage
For this part, we create a snippet with the following content
This snippet should be included in the theme.liquid file using the render tag: {%- render “save-recent-collections” -%}. This snippet will be loaded in every page and will update an Array of recently viewed collections in LocalStorage when a collection page is visited. The default maximum size of the array is 20, but it can be changed adding the parameter max_quantity to the render tag in the following way: {%- render “save-recent-collections”, max_quantity : 10 -%}.
2) Rendering the collection data
To render the data of a specific collection, we are going to use a section, so we can retrieve it using the Section Rendering API. Since this will be fetched as part of the collection template, we have access to the collection object, so we can use all the attributes and metafields of the collection we want to display.
Here is a sample code of a container that includes the title, image and url of the collection. In this case, we use the featured image of the first product of the collection when the collection doesn’t have a default image.
3) Rendering the complete list of recent viewed collections
To render the complete list of recent collections, we will create another snippet. We use this snippet to iterate over the array from LocalStorage created in Step 1, fetch the collection container for each collection and add it to the list container. This snippet can be added anywhere in the shop using the render tag.
https://gist.github.com/emiliotapia/65495d8580890c815a85da4f40dca1d4#file-recent-collections-liquid
As we previously mentioned, we use the Section Rendering API, so we make a request to /collections/collection-handle?section_id=recent-collection-item for each collection to get the corresponding container (we ignore the current collection when the snippet is included in a collection page). In this case, recent-collection-item is the name of the section we created in Step 2. Please keep in mind that the response of the request will be contained in an extra <div> tag that we need to remove.
Also, we use a variable to determine the number of collections we are going to display. We can add the quantity parameter to the render tag.If the parameter is not included, a default value of 4 will be used.