Debian Codegraph @

docs/content/en/functions/transform/PortableText.md

raw
1 ---
2 title: transform.PortableText
3 description: Returns the given Portable Text converted to Markdown.
4 categories: []
5 keywords: []
6 params:
7 functions_and_methods:
8 returnType: string
9 signatures: [transform.PortableText MAP]
10 ---
11
12 {{< new-in 0.145.0 />}}
13
14 ## Usage
15
16 [Portable Text][] is a JSON structure that represents rich text content in the [Sanity][] CMS. In Hugo, this function is typically used in a [content adapter][] that creates pages from Sanity data.
17
18 Supported types:
19
20 - `block` and `span`
21 - `image`. Note that the image handling is currently basic; we link to the `asset.url` using `asset.altText` as the image alt text and `asset.title` as the title. For more fine-grained control you may want to process the images in an [image render hook][].
22 - `code` (see the [code-input][] plugin). Code will be rendered as fenced code blocks with any file name provided passed as a Markdown attribute.
23
24 > [!NOTE]
25 > 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][].
26
27 ## Examples
28
29 The following example creates pages from Sanity data using a content adapter.
30
31 ### Content Adapter
32
33 ```go-html-template {file="content/_content.gotmpl" copy=true}
34 {{ $projectID := "mysanityprojectid" }}
35 {{ $useCached := true }}
36 {{ $api := "api" }}
37 {{ if $useCached }}
38 {{/* See https://www.sanity.io/docs/api-cdn */}}
39 {{ $api = "apicdn" }}
40 {{ end }}
41 {{ $url := printf "https://%s.%s.sanity.io/v2021-06-07/data/query/production" $projectID $api }}
42
43 {{ $q := `*[_type == 'post']{
44 title, publishedAt, summary, slug, body[]{
45 ...,
46 _type == "image" => {
47 ...,
48 asset->{
49 _id,
50 path,
51 url,
52 altText,
53 title,
54 description,
55 metadata {
56 dimensions {
57 aspectRatio,
58 width,
59 height
60 }
61 }
62 }
63 }
64 },
65 }`
66 }}
67 {{ $body := dict "query" $q | jsonify }}
68 {{ $opts := dict "method" "post" "body" $body }}
69 {{ $r := resources.GetRemote $url $opts }}
70 {{ $m := $r | transform.Unmarshal }}
71 {{ $result := $m.result }}
72 {{ range $result }}
73 {{ if not .slug }}
74 {{ continue }}
75 {{ end }}
76 {{ $markdown := transform.PortableText .body }}
77 {{ $content := dict
78 "mediaType" "text/markdown"
79 "value" $markdown
80 }}
81 {{ $params := dict
82 "portabletext" (.body | jsonify (dict "indent" " "))
83 }}
84 {{ $page := dict
85 "content" $content
86 "kind" "page"
87 "path" .slug.current
88 "title" .title
89 "date" (.publishedAt | time )
90 "summary" .summary
91 "params" $params
92 }}
93 {{ $.AddPage $page }}
94 {{ end }}
95 ```
96
97 ### Sanity setup
98
99 The following outlines a suitable Sanity studio setup for the above example.
100
101 ```ts {file="sanity.config.ts" copy=true}
102 import {defineConfig} from 'sanity'
103 import {structureTool} from 'sanity/structure'
104 import {visionTool} from '@sanity/vision'
105 import {schemaTypes} from './schemaTypes'
106 import {media} from 'sanity-plugin-media'
107 import {codeInput} from '@sanity/code-input'
108
109 export default defineConfig({
110 name: 'default',
111 title: 'my-sanity-project',
112
113 projectId: 'mysanityprojectid',
114 dataset: 'production',
115
116 plugins: [structureTool(), visionTool(), media(),codeInput()],
117
118 schema: {
119 types: schemaTypes,
120 },
121 })
122 ```
123
124 Type/schema definition:
125
126 ```ts {file="schemaTypes/postType.ts" copy=true}
127 import {defineField, defineType} from 'sanity'
128
129 export const postType = defineType({
130 name: 'post',
131 title: 'Post',
132 type: 'document',
133 fields: [
134 defineField({
135 name: 'title',
136 type: 'string',
137 validation: (rule) => rule.required(),
138 }),
139 defineField({
140 name: 'summary',
141 type: 'string',
142 validation: (rule) => rule.required(),
143 }),
144 defineField({
145 name: 'slug',
146 type: 'slug',
147 options: {source: 'title'},
148 validation: (rule) => rule.required(),
149 }),
150 defineField({
151 name: 'publishedAt',
152 type: 'datetime',
153 initialValue: () => new Date().toISOString(),
154 validation: (rule) => rule.required(),
155 }),
156 defineField({
157 name: 'body',
158 type: 'array',
159 of: [
160 {
161 type: 'block',
162 },
163 {
164 type: 'image'
165 },
166 {
167 type: 'code',
168 options: {
169 language: 'css',
170 languageAlternatives: [
171 {title: 'HTML', value: 'html'},
172 {title: 'CSS', value: 'css'},
173 ],
174 withFilename: true,
175 },
176 },
177 ],
178 }),
179 ],
180 })
181 ```
182
183 Note that the above requires some additional plugins to be installed:
184
185 ```sh
186 npm i sanity-plugin-media @sanity/code-input
187 ```
188
189 ```ts {file="schemaTypes/index.ts" copy=true}
190 import {postType} from './postType'
191
192 export const schemaTypes = [postType]
193 ```
194
195 ### Server setup
196
197 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:
198
199 <!-- markdownlint-disable MD049 -->
200 {{< code-toggle file=hugo >}}
201 [HTTPCache]
202 [[HTTPCache.polls]]
203 disable = false
204 low = '30s'
205 high = '3m'
206 [HTTPCache.polls.for]
207 includes = ['https://*.*.sanity.io/**']
208
209 [caches.getresource]
210 dir = ':cacheDir/:project'
211 maxAge = "5m"
212 {{< /code-toggle >}}
213 <!-- markdownlint-enable MD049 -->
214
215 The polling above will be used when running the server/watch mode and rebuilds when you push new content to Sanity.
216
217 See [Caching in resources.GetRemote][] for more fine-grained control.
218
219 [Caching in resources.GetRemote]: /functions/resources/getremote/#caching
220 [Portable Text]: https://www.portabletext.org/
221 [RFC 7234]: https://tools.ietf.org/html/rfc7234
222 [Sanity]: https://www.sanity.io/
223 [code-input]: https://www.sanity.io/plugins/code-input
224 [content adapter]: /content-management/content-adapters/
225 [image render hook]: /render-hooks/images/
226 [render hooks]: /render-hooks/