Skip to content

Instantly share code, notes, and snippets.

@jeremycaldwell
Last active September 18, 2020 20:31
Show Gist options
  • Save jeremycaldwell/d0240a2b439c4493b18d7909f4747306 to your computer and use it in GitHub Desktop.
Save jeremycaldwell/d0240a2b439c4493b18d7909f4747306 to your computer and use it in GitHub Desktop.
Sanity.io components in 11ty
const groq = require('groq')
const BlocksToMarkdown = require('@sanity/block-content-to-markdown')
const client = require('../utils/sanityClient.js')
const serializers = require('../utils/serializers')
const overlayDrafts = require('../utils/overlayDrafts')
const hasToken = !!client.config().token
function generateBasicpage (basicpage) {
return {
...basicpage,
body: BlocksToMarkdown(basicpage.body, { serializers, ...client.config() })
}
}
async function getBasicpages () {
const filter = groq`*[_type == "basicpage" && defined(slug)]`
const projection = groq`{
_id,
publishedAt,
title,
slug,
pageBuilder,
body[]{
...,
children[]{
...,
// Join inline reference
_type == "authorReference" => {
// check /studio/documents/authors.js for more fields
"name": @.author->name,
"slug": @.author->slug
}
}
},
}`
const order = `| order(publishedAt asc)`
const query = [filter, projection, order].join(' ')
const basicpages = await client.fetch(query).catch(err => console.error(err))
const reducedBasicpages = overlayDrafts(hasToken, basicpages)
const prepareBasicpages = reducedBasicpages.map(generateBasicpage)
return prepareBasicpages
}
module.exports = getBasicpages
---
layout: layouts/base.njk
---
<article>
<h1>{{ basicpage.title }}</h1>
{{ basicpage.body | markdownify | safe }}
{% for component in basicpage.pageBuilder %}
{% set componentType = component._type %}
{% if componentType == 'hero' %}
{%- include "components/hero.njk" -%}
{% elseif componentType == 'textWithIllustration' %}
{%- include "components/textWithIllustration.njk" -%}
{% endif %}
{% endfor %}
</article>
{# Styling #}
{% set css %}{% include "_site/dist/css/components/hero.css" %}{% endset %}
{# Markup #}
<section class="hero component">
<style>{{ css | cssmin | safe }}</style>
<header class="hero__content">
<div class="hero__inner">
<div class="hero__body">
<h2 class="hero__title">{{ component.heading }}</h2>
<p class="hero__tagline">{{ component.tagline }}</p>
</div>
</div>
</header>
<div class="hero__image"><img src="{% croppedUrlFor component.image, '1290', '500' %}" alt="{{ component.image.alt }}" /></div>
</section>
---
layout: layouts/basicpage
tags:
- myBasicpages
pagination:
alias: basicpage
data: basicpages
size: 1
addAllPagesToCollections: true
permalink: /{{ basicpage.slug.current | slug }}/index.html
---
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment