martin66 martin66 - 1 year ago 137
Javascript Question

HTML template to Javascript String Literals

thanks for any feedback...

I have an HTML template with JS string literals embedded...

<html>
<head>
<title>${title}</title>
</head>
<body>
User name: ${user.name}
</body>
</html>


I'm then doing...

let temp = require('./template.html')

return temp; // <--- I need this to return the compiled html


How can I get the string literals to render?

Is it even possible to do this?

I need the 'temp' variable to return as a compiled string so that I can insert it to a document.write later on in the code.

Thanks.

Answer Source

You can create a new Function to turn it into a string template

return new Function("title","user","return `" + temp + "`;")(title,user);

As pointed out by T.J you will need to know all the variables used in the template and include them as arguments to the function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download