Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active January 22, 2020 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save james2doyle/8f4ac8b42b4a07136ab4a3580a204725 to your computer and use it in GitHub Desktop.
Save james2doyle/8f4ac8b42b4a07136ab4a3580a204725 to your computer and use it in GitHub Desktop.
Gets a Shopify section and parses it as JSON
/**
* Get section from the rendering API
* @see https://help.shopify.com/en/themes/development/sections/section-rendering-api
*
* @param {string} section
*
* @returns {Promise<Object>}
*/
export async function getSection(section) {
try {
// call the rendering API
const data = await (await fetch(`/?section_id=${section}`)).text();
// create a DOMParser and get the inside content of the section
const parser = new DOMParser();
const node = parser.parseFromString(data.toString(), 'text/html').querySelector('.shopify-section');
if (!node) {
console.error('No node found in', data);
return {};
}
const content = (node.textContent || '').trim();
// parse that content as JSON
return JSON.parse(content);
} catch (e) {
console.error(e);
}
return {};
}
{% comment %}https://help.shopify.com/en/themes/development/sections/section-rendering-api{% endcomment %}
{% comment %}request.page_type will be "index" when using the section rendering API{% endcomment %}
{% comment %}content_for_header will contain the query string in the request{% endcomment %}
{%- if request.page_type == 'index' and content_for_header contains 'section_id' -%}
{
{%- for block in section.blocks -%}
{%- assign slug = block.settings.title | downcase -%}
"{{ slug }}": {{- block.settings | json -}}{%- unless forloop.last -%},{%- endunless -%}
{%- endfor -%}
}
{%- else -%}
{%- for block in section.blocks -%}
{%- assign slug = block.settings.title | downcase -%}
<div id="{{ slug }}">{{ block.settings.title }}</div>
{%- endfor -%}
{%- endif -%}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment