Add transform.PortableText

Using this in a content adapter could look like this:

```handlebars
{{ $projectID := "<myproject>" }}
{{ $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 }}
{{ $t := debug.Timer "sanity.get" }}
{{ $r := resources.GetRemote $url $opts }}
{{ $t.Stop }}
{{ $m := $r | transform.Unmarshal }}
{{ $result := $m.result }}
{{ $t := debug.Timer "sanity.parse" }}
{{ range $result }}
  {{ if not .slug }}
    {{ continue }}
  {{ end }}
  {{ $markdown := transform.PortableText .body }}
  {{ $t.Stop }}
  {{ $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 }}
```
This commit is contained in:
Bjørn Erik Pedersen 2025-02-21 16:22:01 +01:00
parent ab9e545760
commit 04f21b4d80
4 changed files with 54 additions and 0 deletions

View file

@ -349,3 +349,33 @@ disableKinds = ['page','rss','section','sitemap','taxonomy','term']
b.AssertFileExists("public/index.html", true)
b.AssertFileContent("public/index.html", `{"a":{"b":1},"c":{"d":2}}`)
}
func TestPortableText(t *testing.T) {
files := `
-- hugo.toml --
-- assets/sample.json --
[
{
"_key": "a",
"_type": "block",
"children": [
{
"_key": "b",
"_type": "span",
"marks": [],
"text": "Heading 2"
}
],
"markDefs": [],
"style": "h2"
}
]
-- layouts/index.html --
{{ $markdown := resources.Get "sample.json" | transform.Unmarshal | transform.PortableText }}
Markdown: {{ $markdown }}|
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html", "Markdown: ## Heading 2\n|")
}