Mario
Mario

Reputation: 4988

How to render html inside Template literals?

I explain my scenario, the users enter content through a WYSIWYG editor that is persisted in the database, in another place of the application this content and another one is obtained through an ajax request, here I use template literals to build a html structure with the data that is finally inserted into the view using innerHTML in a destination DOM element.

I require that the content that was added through the WYSIWYG editor be displayed as html, with lodash function _.unescape () I get the free content of html special characters, but this is not shown as html but as a html string

I share the general idea of ​​the implementation:

Template literal

`...
<div>${getHTML(dataset.message)}</div>
...`

Javascript

function getHTML(message) {
    const html = _.unescape(message).replace('\\', '');
    const parser = new DOMParser();
    const dom = parser.parseFromString(html, 'text/html')

    return dom;
}

Output

[object HTMLDocument]

If instead of the dom variable I return the html variable in the view I get for example <p>some content <strong>goes here</strong></ p> and I require this content to be displayed as regular view html

Any idea please about showing the content as html?

Thanks

Upvotes: 7

Views: 16207

Answers (2)

user3210641
user3210641

Reputation: 1631

The reason this happens is because DOMParser returns a HTMLDocument object and when you try to set HTMLDocument object as innerHTML of any element it calls toString() of this object - which is [object HTMLDocument].

You can try this yourself:

const html = '<div>Some html content</div>';

const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");

console.log(doc.toString()); // [object HTMLDocument]

Good news is, that in your case you don't need the DOMParser at all. All you need to unescape the given string and set it as innerHTML of your element:

// Your modified getHTML function
const getHTML = message => _.unescape(message).replace('\\', '');

// Container in which your want to render the HTML
const container = document.getElementById('container');

// Dummy HTML representing your data from the database
const html = _.escape('<h1>Your content</h1>');

// Dummy template representing your template literal
const template = `
<div>
  ${getHTML(html)}
</div>
`;

// Set the resolved dummy template as content of the dummy container
container.innerHTML = template;
<div id="container"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

Upvotes: 2

Hira Kumar Maharjan
Hira Kumar Maharjan

Reputation: 278

Yeap this will work return dom.firstChild.innerHTML;

Upvotes: -2

Related Questions