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
Preloading Images With JavaScript
Crockford'S Prototypal Inheritance - Issues With Nested Objects
Check If a Value Is an Object in JavaScript
How to Replace All Line Breaks in a String With ≪Br /≫ Elements
How to Determine If a Variable Is 'Undefined' or 'Null'
Difference Between Variable Declaration Syntaxes in JavaScript (Including Global Variables)
Tainted Canvases May Not Be Exported
How to Use Backslashes (\) in a String
Read a File One Line At a Time in Node.Js
Npm Not Installing Returns Error Consistently
How to Install Jslint on Ubuntu
Rails 4 Turbolinks Make Form Submit Multiple Times
Rails: Post 422 (Unprocessable Entity) in Rails? Due to the Routes or the Controller
How to Use a Ruby Loop Inside of Haml's :JavaScript Region