#Parse HTML into Astro component

1 messages · Page 1 of 1 (latest)

steep ridgeBOT
#

Hi @warped creek. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, you can use the set:html directive in Astro to inject HTML strings into an element. This is similar to setting el.innerHTML in JavaScript. Here's how you can use it:

---
const htmlString = 'Con Happy Weekend(9) HSBC disfruta beneficios especiales.<br />Promociones, descuentos(9) y Meses sin Intereses* en cientos de comercios.<br />';
---
<p set:html={htmlString} />

However, please be aware that the value is not automatically escaped by Astro. Make sure that you trust the value, or that you have escaped it manually before passing it to the template. Forgetting to do this will open you up to Cross Site Scripting (XSS) attacks.

You can also use set:html on a <Fragment /> to avoid adding an unnecessary wrapper element. This can be especially useful when fetching HTML from a CMS.

---
const cmsContent = await fetchHTMLFromMyCMS();
---
<Fragment set:html={cmsContent} />

For more information, you can refer to the Astro documentation on set:html (https://docs.astro.build/en/reference/directives-reference/#sethtml).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@warped creek kapa.ai is still learning and improving, please let us know how it did by reacting below

warped creek
#

@steep ridge Is there a native way to escape this tags before inserting the HTML into the component?

steep ridgeBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Astro doesn't provide a built-in way to escape HTML tags before inserting them into a component. However, you can use a JavaScript function to manually escape the HTML content before passing it to set:html. Here's an example of how you can do this:

---
const htmlString = 'Con Happy Weekend(9) HSBC disfruta beneficios especiales.<br />Promociones, descuentos(9) y Meses sin Intereses* en cientos de comercios.<br />';

function escapeHTML(html) {
  const div = document.createElement('div');
  div.textContent = html;
  return div.innerHTML;
}

const escapedHTML = escapeHTML(htmlString);
---
<p set:html={{escapedHTML}} />

Please note that this code uses the document.createElement method, which is not available in server-side rendering environments. If you're using Astro in a server-side context, you might need to use a server-side compatible library or method to escape your HTML.

For more information on how to use set:html, you can refer to the Astro documentation (https://docs.astro.build/en/reference/directives-reference/#sethtml).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: