I am attempting to use Astro for the first time, and I am also attempting to use Prismic as the data source. In my Prismic project, I have a number of rich text fields, and I simply want to render them as HTML in my Astro component. Per the Prismic docs, I need to render them using asHTML, which is part of @prismicio/helpers.
In my use case, I have, as an example, a header_text
and a test_item_1
field in prismic. Using this code below, I am able to fetch the data and store it in a couple variables.
---
import Layout from '../layouts/Layout.astro';
import * as prismicH from '@prismicio/helpers';
import {getFrontPage} from '../prismic.js';
const fp = await getFrontPage();
const {data} = fp.results[0];
const headerText = prismicH.asHTML(data.header_text);
const textItem1 = prismicH.asHTML(data.text_item_1);
When I use the <Debug>
component to show me data
, I get this:
{
"header_text": [
{
"type": "paragraph",
"text": "We have met the needs of Manufacturers, Fabricators,\nInstallers, Inventors, and Machine Shops for over 22 Years.\nIn Oregon and across the United States.",
"spans": []
}
],
"text_item_1": [
{
"type": "heading3",
"text": "Our Clients",
"spans": [
{
"start": 0,
"end": 11,
"type": "strong"
}
]
},
{
"type": "paragraph",
"text": "We work with Manufacturers, Fabricators, Installers, Inventors, and Machine Shops who need a better laser mark, shorter lead times, and cost-effective pricing.",
"spans": []
},
{
"type": "paragraph",
"text": " ",
"spans": []
},
{
"type": "paragraph",
"text": "For these organizations, we are a reasonably priced, efficient, and high-quality operation that can guarantee an exceptional mark on various products and material types.",
"spans": []
}
],
}
which is what I should be passing to asHTML()
per the docs.
However, when I display the HTML in the template
{headerText}
{textItem1)
I get the escaped HTML, instead of the rendered HTML
<p>We have met the needs of Manufacturers, Fabricators,<br />Installers, Inventors, and Machine Shops for over 22 Years.<br />In Oregon and across the United States.</p>
<h3><strong>Our Clients</strong></h3><p>We work with Manufacturers, Fabricators, Installers, Inventors, and Machine Shops who need a better laser mark, shorter lead times, and cost-effective pricing.</p><p> </p><p>For these organizations, we are a reasonably priced, efficient, and high-quality operation that can guarantee an exceptional mark on various products and material types.</p>
So as far as I can tell, I'm doing everything correctly. Why is my HTML being escaped? I don't have any links in my text, so I don't need a linkResolver or HTML serializer.
So the issue wasn't with Prismic, but Astro. Astro has the set:html template directive, which is responsible for displaying the unescaped HTMl (similar to v-html in Vue).
In my template, all I had to do was
<div set:html={headerText}></div>
and it displays the HTML as expected.