How to use channel metafields in your theme
Once you have created your channel metafield, and you have enabled storefront access, it can be queried using GraphQL.
One way to do this would be simply todesign your query and then make a JavaScript request. The downside of this is that any changes then become "client-side".
We recommend testing out new graphQL queries in the storefront API playground first.
However, there's a better way. A powerful part of stencil themes is the ability to add GraphQL queries to the front matter. When you do this, BigCommerce makes the response to this request available server-side. This means you can use GraphQL data within your template.
For example, this query will search for a metafield with key "space_48" and key "top-navigation". By adding it to the theme front matter a new object will be available for access in the template, e.g. gql.
--- category: shop_by_price: true products: limit: {{theme_settings.categorypage_products_per_page}} gql: "query channelMetafields() { channel { metafields(namespace:\"megamenubuilder\",keys: [\"top-navigation\"]) { edges { node { key value } } } } } " ---
Assuming that this was raw HTML then it could be outputted at the top of the page by adding this to the category.html template and using triple braces `{{{ }}}`:
<div class="page-content" id="product-listing-container"> {{#each gql.data.channel.metafields.edges}} {{{node.value}}} {{/each}} {{> components/category/product-listing}} {{{region name="category_below_content"}}} </div>
Alternatively, if the metafield was used to enable/disable functionality per channel. It could be checked within a condition like so:
{{#each gql.data.channel.metafields.edges}} {{#eq node.value "Yes"}} The flag was enabled for this channel. {{/eq}} {{/each}}
If you have more than one metafield key selected in your query, you can perform a check based on key name:
{{#each gql.data.channel.metafields.edges}} {{#and (if node.key '==' "test_flag") (if node.value '==' "Yes") }} The flag was enabled for this channel. {{/and}} {{#if node.key '===' "test_content"}} {{{node.value}}} {{/if}} {{/each}}