3

I'd like to create an excerpt from a (portable) text field. Is this something that is possible?

I know I can get the text value back using pt::text(body) and I can get values such as length from that. Is there any way to cut the text after n characters or words?

Designer023
  • 1,902
  • 1
  • 26
  • 43

1 Answers1

3

I have solved this now. I feel like it's a bit of a hack, but essentially...

  1. Get the string of the body as above: pt::text(body)
  2. Split the string into an array of every character: string::split(bodyString, "")
  3. truncate it to 255 characters: [0..255]
  4. Join it back together: array::join(truncated, "")
  5. Add an ellipsis to the end: + "..."

Joined together it can either be a set of queries piped together:

*[_type == "article" && draft != true ] | order(publishedOn desc)[0..5] {
  "excerpt": (pt::text(body)),
} | {
 "excerpt": string::split(excerpt, "")[0..255]
} | {
  "excerpt": array::join(excerpt, "") + "..."
}

Or as one query:

*[_type == "article" && draft != true ] | order(publishedOn desc)[0..5] {
     "excerpt": array::join(string::split((pt::text(body)), "")[0..255], "") + "..."
}
Designer023
  • 1,902
  • 1
  • 26
  • 43