I am experiencing an issue when attempting to render HTML content retrieved from a Collection field through an HTML Embed on my website. I am injecting HTML content into my Collection via an API. However, when I try to display this content using an HTML Embed with the “Add Field” function in Webflow, the HTML code is displayed as plain text on the page and not being rendered as HTML.
For a comparison:
When I insert the same HTML code directly into the HTML Embed (without using the “Add Field” function), the HTML is rendered correctly on the page.
However, when I use the “Add Field” function to pull the HTML content from the Collection, the HTML code is not rendered and is displayed as plain text.
I have followed the standard procedures for embedding HTML content and utilizing the “Add Field” function as per Webflow documentation but am still facing this issue.
I am seeking your assistance in resolving this issue as it’s crucial for displaying dynamic HTML content on my website correctly. Is there a specific setting or step that I might be missing to ensure the HTML content from the Collection field is rendered correctly through the HTML Embed?
Hey Luca,
I spent some time figuring out a solution, & I have found one that is very simple.
Within the HTML, create a div with an ID, & add the text that you want to display as HTML. Then create a function that grabs the text content from the div & converts it to HTML.
Here is the code for you
<div id='html-wrap'>
%{{{ Data From CMS }}}%
</div>
<script>
function stringToHTML (wrapId) {
const htmlWrap = document.getElementById(wrapId)
const code = htmlWrap.innerText
htmlWrap.innerHTML = code
}
stringToHTML('html-wrap');
</script>
P.S: Just note you will not be able to preview these changes within the designer since we’re using the script tags. So you can only preview these changes on the published site, if your website is live on a domain, then just publish to the webflow.io staging, to test it.
Dylan’s solution is good but it looks like you may be approaching the problem incorrectly.
Plain text CMS fields are not designed for HTML content. Typically, if you can, you’d want to use a Rich Text field for that. If your HTML is not rich-text compatible, you might be able to achieve that by using an HTML embed inside of the rich text, though this can be challenging via the API.
Rich text fields cannot be + add field inserted inside of HTML embeds, you’d just bind this directly to a rich text element instead.
Anything you + add field insert inside of an HTML embed will get HTML-encoded, which is why you’re having encoding issues.
Changing your approach should eliminate the problem but if you’re stuck, you can use a plain text field and then HTML decode it.
There’s a nocode attribute solution for that if you want-