Chuck
Chuck

Reputation: 391

How to render a template string as HTML?

Let's say I have a simple template string :

const foo = `<div>foo</div>`;

How do I go about rendering this template string as HTML ? It renders it as plain text if I do the following :

return({ foo });

Output:

<div>foo</div>

Expected output:

foo

Upvotes: 4

Views: 6964

Answers (4)

mahi
mahi

Reputation: 1

if you want to show the string of html as html page its better to do this:

<text>{{ info | safe }}</text>

Upvotes: 0

Matt Condit
Matt Condit

Reputation: 27

You note reactjs as a tag here. Instead of specifying the html as a string, make foo a functional react component.

To do that, make sure you have import React as 'react';.
Then, set foo as the functional component, i.e.:

const foo = () => <div>foo</div>;

Then, you can use that wherever you please. React components are just functions (or classes) that return jsx.

Your question is fairly open-ended, so you may be looking for some of the above answers, but this is one approach.

Upvotes: 1

zer00ne
zer00ne

Reputation: 44118

Off the top of my head there's 2 ways to parse a string (doesn't have to be a tl) into HTML: .innerHTML property and the more powerful .insertAdjacentHTML() method.

Demo

var tl = `
  <video src='http://media6000.dropshots.com/photos/1381926/20170326/005611.mp4' controls width='320'></video>`;
  
document.body.innerHTML = tl;

document.body.insertAdjacentHTML('afterbegin', tl);
   

Upvotes: 0

Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36219

I think what you try to do is

const foo = `<div>foo</div>`;
<div dangerouslySetInnerHTML={{ __html: foo }}></div>

Related question.

React documentation.

Upvotes: 6

Related Questions