Adding Fragments to collection query
This example shows how to add fragments to a collection query, which will help you to get the current fragment and also add new fragments to the collection.
Introduction
This example shows how to add fragments to a collection query, which will help you to get the current fragment and also add new fragments to the collection. This will be helpfull in getting additional data from collection query that is available in shopify.
Steps
- In
theme/src/index.jsadd the following code:
import {
CollectionFragments,
} from './functions';
- Add the following code inside
activatefunction:
CollectionFragments();- In
theme/src/functions.jsdefineCollectionFragments()function. following is an example of using fragments in collection query. In this example we are adding two fragments to the collection query. Here you can see i have added two fragmentscollectionDescriptionFragmentandcollectionTitleHandleFragmentto the collection query. You can add as many fragments as you want.collectionDescriptionFragmentwill return the description of the collection andcollectionTitleHandleFragmentwill return the title and handle of the collection. you can see this documentation for more available fields for this like thedescription,title,handleetc.
export function CollectionFragmentsTest() {
const fragment1 = `
fragment collectionDescriptionFragment on Collection {
description
}
`;
const fragment2 = `
fragment collectionTitleHandleFragment on Collection {
title
handle
}
`;
appmaker.addFilter('collection-fragments', 'theme-bsc', (fragments) => {
console.log('fragments', fragments); // existing fragments which will be added to the collection query by default.
fragments.push({
name: 'collectionDescriptionFragment', // this should be unique and should be same as the name of the fragment.
fragment: fragment1,
});
fragments.push({
name: 'collectionTitleHandleFragment', // this should be unique and should be same as the name of the fragment.
fragment: fragment2,
});
return fragments;
});
}