Skip to content

Commit

Permalink
Add transform.PortableText
Browse files Browse the repository at this point in the history
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 }}
```
  • Loading branch information
bep committed Feb 25, 2025
1 parent ab9e545 commit 04f21b4
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 0 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ require (
github.com/bep/goat v0.5.0
github.com/bep/godartsass/v2 v2.3.2
github.com/bep/golibsass v1.2.0
github.com/bep/goportabletext v0.1.0
github.com/bep/gowebp v0.3.0
github.com/bep/helpers v0.5.0
github.com/bep/imagemeta v0.8.4
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ github.com/bep/godartsass/v2 v2.3.2 h1:meuc76J1C1soSCAnlnJRdGqJ5S4m6/GW+8hmOe9tO
github.com/bep/godartsass/v2 v2.3.2/go.mod h1:Qe5WOS9nVJy7G0jHssXPd3c+Pqk/f7+Tm6k/vahbVgs=
github.com/bep/golibsass v1.2.0 h1:nyZUkKP/0psr8nT6GR2cnmt99xS93Ji82ZD9AgOK6VI=
github.com/bep/golibsass v1.2.0/go.mod h1:DL87K8Un/+pWUS75ggYv41bliGiolxzDKWJAq3eJ1MA=
github.com/bep/goportabletext v0.1.0 h1:8dqym2So1cEqVZiBa4ZnMM1R9l/DnC1h4ONg4J5kujw=
github.com/bep/goportabletext v0.1.0/go.mod h1:6lzSTsSue75bbcyvVc0zqd1CdApuT+xkZQ6Re5DzZFg=
github.com/bep/gowebp v0.3.0 h1:MhmMrcf88pUY7/PsEhMgEP0T6fDUnRTMpN8OclDrbrY=
github.com/bep/gowebp v0.3.0/go.mod h1:ZhFodwdiFp8ehGJpF4LdPl6unxZm9lLFjxD3z2h2AgI=
github.com/bep/helpers v0.5.0 h1:rneezhnG7GzLFlsEWO/EnleaBRuluBDGFimalO6Y50o=
Expand Down Expand Up @@ -217,6 +219,8 @@ github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1
github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ=
github.com/go-quicktest/qt v1.101.0 h1:O1K29Txy5P2OK0dGo59b7b0LR6wKfIhttaAhHUyn7eI=
github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow=
github.com/go-test/deep v1.0.8 h1:TDsG77qcSprGbC6vTN8OuXp5g+J+b5Pcguhf7Zt61VM=
github.com/go-test/deep v1.0.8/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
github.com/gobuffalo/flect v1.0.3 h1:xeWBM2nui+qnVvNM4S3foBhCAL2XgPU+a7FdpelbTq4=
Expand Down
19 changes: 19 additions & 0 deletions tpl/transform/transform.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ import (
"strings"
"sync/atomic"

bp "github.com/gohugoio/hugo/bufferpool"

"github.com/bep/goportabletext"

"github.com/gohugoio/hugo/cache/dynacache"
"github.com/gohugoio/hugo/common/hashing"
"github.com/gohugoio/hugo/common/hugio"
Expand Down Expand Up @@ -197,6 +201,21 @@ func (ns *Namespace) Plainify(s any) (template.HTML, error) {
return template.HTML(tpl.StripHTML(ss)), nil
}

// PortableText converts the portable text in v to Markdown.
// We may add more options in the future.
func (ns *Namespace) PortableText(v any) (string, error) {
buf := bp.GetBuffer()
defer bp.PutBuffer(buf)
opts := goportabletext.ToMarkdownOptions{
Dst: buf,
Src: v,
}
if err := goportabletext.ToMarkdown(opts); err != nil {
return "", err
}
return buf.String(), nil
}

// ToMath converts a LaTeX string to math in the given format, default MathML.
// This uses KaTeX to render the math, see https://katex.org/.
func (ns *Namespace) ToMath(ctx context.Context, args ...any) (template.HTML, error) {
Expand Down
30 changes: 30 additions & 0 deletions tpl/transform/transform_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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|")
}

0 comments on commit 04f21b4

Please sign in to comment.