Structured Text as HTML

Hi, I’m just wondering if it’s possible for the API to return a HTML string representation of a Structured Text field? There’s some scenarios where I’d rather not always have to do this on the client.

Thanks in advance.

Hello @digi and welcome to the community!

We have a package that does exactly that through a function: structured-text/packages/to-html-string at main · datocms/structured-text · GitHub

Or, if you are using react you can also use our <StructuredText> component to render it: GitHub - datocms/react-datocms: A set of components and utilities to work faster with DatoCMS in React environments

You can see all of the transformation options we have for structured text data right here: GitHub - datocms/structured-text

Thanks, but these all seem like client-side solutions, unless I’m missing something?

They are JavaScript functions, so you can really use them wherever you want (using getStaticProps as an example if you are using NextJS and you want to use it on the server-side)

However, for a “in API” solution we would run into a problem:
Structured Text fields can contain custom blocks inside of them, and the render rules of how to map those custom blocks into HTML need to be provided by the developer. So they can’t really be done directly on the API, as we would have no way of knowing how you would like your custom block to be rendered

With the JavaScript functions/components this is solved by passing a custom renderRule parameter, that can specify how to map certain nodes to HTML, as documented here: react-datocms/ at master · datocms/react-datocms · GitHub

Yeah, that makes sense. I guess for scenarios where I might just have some simple formatting (bold, italic, lists etc.) that can easily render to html, it would be nice to know that’s an option, but not a deal-breaker (hence the Feature requests category) :wink:

Many thanks.

1 Like

sorry if it’s late for the answer, but the point of the structured text field is to output something that is agnostic of the rendering, I don’t think we are going to output HTML as we are trying to do something else here.

I see that your use case makes sense, but maybe can you consider using a text field with Markdown and if at some point you need to switch to structured text you can always migrate to it, it’s not too bad