80dd7b067 theme: Fix border class in render-codeblock template 0d3fde6c9 content: Fix typo 23a4adb29 content: More site => project changes 9243e9f6b content: Rename site configuration to project configuration (phase 2) 330aa2249 content: Miscellaneous edits 25ce893be content: Clarify sort order with PAGE.Rotate b398506dc content: Various dimension improvements c54573d13 content: Use singular form in method section descriptions d9a95fe54 content: Improve description of PAGE.Rotate 154f30600 content: Fix link c71bd2776 content: Address Markdown linting error 72c88e68e content: Improve pages related to content dimensions b85afa645 content: Fix formatting 7aaca8947 content: More site-to-project changes 8e1579030 content: Update quick start guide f7ba1fde2 content: Make new-in into a note 8b9d51584 theme: Address TailwindCSS warnings 3a4c2a25c theme: Address Hugo v0.156.0 deprecations 4f1a2bd7b content: Improve glossary entries 21bcd23a6 content: Update glossary entry c72ef1116 content: Update quick start guide c0737ffab content: Add typography plugin to TailwindCSS example 80bcb868e content: Remove Site.AllPages from examples 2b9ba5831 content: Replace Page.Sites and Site.Sites with hugo.Sites 2cdcc2556 content: Remove outdated badges 5a4beb530 content: Replace Site.Data with hugo.Data de4651b5d content: Update glossary entry 2302825a7 content: Add hugo.Data and note other deprecations bac5da4b5 content: Add hugo.Sites and update the other Sites methods 0f7d99153 content: Add Site.IsDefault f888f33bb content: Update glossary entries 65311c2de content: Include the "build" subcommand where appropriate 4991320d2 content: Standard shell language code in info strings b16d9f162 theme: Style todo lists f121450c6 content: Update version references 5a81dd8c2 content: Update CLI documentation f3ae0ce86 content: Rename site configuration to project configuration (phase 1) 9c8327119 content: Miscellaneous edits fbff91e22 Update HUGO_VERSION to 0.156.0 2ec625ae8 content: Restore snap installation instructions fc8c246b8 content: Clarify module initialization git-subtree-dir: docs git-subtree-split: 80dd7b067c31c28b13c51f3ac4636890509a4bb7
5.8 KiB
title, description, categories, keywords, params
| title | description | categories | keywords | params | |||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| transform.PortableText | Converts Portable Text to Markdown. |
|
{{< new-in "0.145.0" />}}
Portable Text is a JSON structure that represent rich text content in the Sanity CMS. In Hugo, this function is typically used in a Content Adapter that creates pages from Sanity data.
Types supported
blockandspanimage. Note that the image handling is currently very simple; we link to theasset.urlusingasset.altTextas the image alt text andasset.titleas the title. For more fine grained control you may want to process the images in a image render hook.code(see the code-input plugin). Code will be rendered as fenced code blocks with any file name provided passed on as a markdown attribute.
Note
Since the Portable Text gets converted to Markdown before it gets passed to Hugo, rendering of links, headings, images and code blocks can be controlled with Render Hooks.
Example
Content Adapter
{{ $projectID := "mysanityprojectid" }}
{{ $useCached := true }}
{{ $api := "api" }}
{{ if $useCached }}
{{/* See https://www.sanity.io/docs/api-cdn */}}
{{ $api = "apicdn" }}
{{ end }}
{{ $url := printf "https://%s.%s.sanity.io/v2021-06-07/data/query/production" $projectID $api }}
{{/* prettier-ignore-start */ -}}
{{ $q := `*[_type == 'post']{
title, publishedAt, summary, slug, body[]{
...,
_type == "image" => {
...,
asset->{
_id,
path,
url,
altText,
title,
description,
metadata {
dimensions {
aspectRatio,
width,
height
}
}
}
}
},
}`
}}
{{/* prettier-ignore-end */ -}}
{{ $body := dict "query" $q | jsonify }}
{{ $opts := dict "method" "post" "body" $body }}
{{ $r := resources.GetRemote $url $opts }}
{{ $m := $r | transform.Unmarshal }}
{{ $result := $m.result }}
{{ range $result }}
{{ if not .slug }}
{{ continue }}
{{ end }}
{{ $markdown := transform.PortableText .body }}
{{ $content := dict
"mediaType" "text/markdown"
"value" $markdown
}}
{{ $params := dict
"portabletext" (.body | jsonify (dict "indent" " "))
}}
{{ $page := dict
"content" $content
"kind" "page"
"path" .slug.current
"title" .title
"date" (.publishedAt | time )
"summary" .summary
"params" $params
}}
{{ $.AddPage $page }}
{{ end }}
Sanity setup
Below outlines a suitable Sanity studio setup for the above example.
import {defineConfig} from 'sanity'
import {structureTool} from 'sanity/structure'
import {visionTool} from '@sanity/vision'
import {schemaTypes} from './schemaTypes'
import {media} from 'sanity-plugin-media'
import {codeInput} from '@sanity/code-input'
export default defineConfig({
name: 'default',
title: 'my-sanity-project',
projectId: 'mysanityprojectid',
dataset: 'production',
plugins: [structureTool(), visionTool(), media(),codeInput()],
schema: {
types: schemaTypes,
},
})
Type/schema definition:
import {defineField, defineType} from 'sanity'
export const postType = defineType({
name: 'post',
title: 'Post',
type: 'document',
fields: [
defineField({
name: 'title',
type: 'string',
validation: (rule) => rule.required(),
}),
defineField({
name: 'summary',
type: 'string',
validation: (rule) => rule.required(),
}),
defineField({
name: 'slug',
type: 'slug',
options: {source: 'title'},
validation: (rule) => rule.required(),
}),
defineField({
name: 'publishedAt',
type: 'datetime',
initialValue: () => new Date().toISOString(),
validation: (rule) => rule.required(),
}),
defineField({
name: 'body',
type: 'array',
of: [
{
type: 'block',
},
{
type: 'image'
},
{
type: 'code',
options: {
language: 'css',
languageAlternatives: [
{title: 'HTML', value: 'html'},
{title: 'CSS', value: 'css'},
],
withFilename: true,
},
},
],
}),
],
})
Note that the above requires some additional plugins to be installed:
npm i sanity-plugin-media @sanity/code-input
import {postType} from './postType'
export const schemaTypes = [postType]
Server setup
Unfortunately, Sanity's API does not support RFC 7234 and their output changes even if the data has not. A recommended setup is therefore to use their cached apicdn endpoint (see above) and then set up a reasonable polling and file cache strategy in your Hugo configuration, e.g:
{{< code-toggle file=hugo >}} [HTTPCache] HTTPCache.polls disable = false low = '30s' high = '3m' [HTTPCache.polls.for] includes = ['https://..sanity.io/**']
[caches.getresource] dir = ':cacheDir/:project' maxAge = "5m" {{< /code-toggle >}}
The polling above will be used when running the server/watch mode and rebuild when you push new content in Sanity.
See Caching in resources.GetRemote for more fine grained control.