Convert a String to a Template String

Convert a string to a template string

As your template string must get reference to the b variable dynamically (in runtime), so the answer is: NO, it's impossible to do it without dynamic code generation.

But, with eval it's pretty simple:

let tpl = eval('`'+a+'`');

Converting Strings to Template Literals in ES6

Yes, they aren't recursive.

If your starting point is a string containing those placeholders, as far as I know there is no template compiler function. There's eval, of course; [insert all the usual caveats about using eval — only with content you trust, not if you can avoid it, etc., etc. — here].

So for instance:

"use strict";

var x = {"add": "${a + b}"};

var a = 10, b = 20;

console.log(eval("`" + x.add + "`"));

How can I construct a Template String from a regular string?

Is there a way to programmatically construct a Template literal?

No. "programmatically" and "literal" are antithetic (except you are in the realms of compilers).

Template strings should better have been named interpolated string literals or so. Please do not confuse them with templates. If you want to use dynamically created strings for templates, use a template engine of your choice.

Of course template literals might help with the implementation of such, and you might get away with something simple as

function assemble(literal, params) {
return new Function(params, "return `"+literal+"`;"); // TODO: Proper escaping
// ^^^^^^^^ working in real ES6 environments only, of course
}
var template = assemble("Hello, my name is ${name}", "name");
template("Chaim"); // Hello, my name is Chaim

Convert a es6 template string to html element using vanilla javascript

You can use insertAdjacentHTML:

function renderBody(selector = 'body', template) {

const prop = { text: 'foobar' };

const html = `<div id='test'>${prop.text}</div>`;

document.querySelector(selector).insertAdjacentHTML('beforeend', html);

}

renderBody();
div { border: 1px solid }
<h1>test</h1>

How to convert a TemplateLiteral AST node back into template string source code?

You're always going to have quasis.length == expressions.length+1. You just take the first quasi, then the first expression, then the next quasi, then the next expression, etc., until the last quasi.



Related Topics



Leave a reply



Submit