Home >Web Front-end >JS Tutorial >How to Defer ES6 Template Literal Evaluation?
In ES6, template literals allow for string interpolation with dynamic values. However, sometimes we may need to defer the evaluation of the template literal until a later point to incorporate dynamic elements.
Question: How can we write code to defer the evaluation of an ES6 template literal until after we have dynamically created the elements used for interpolation?
Answer: There are several approaches to achieving this:
Using Plain Strings:
Utilize plain string literals instead of template strings to avoid immediate evaluation. The interpolation placeholder values can be formatted using a custom prototype method like this:
String.prototype.format = function() { var args = arguments; return this.replace(/$\{p(\d)\}/g, function(match, id) { return args[id]; }); }; console.log("Hello, ${p0}. This is a ${p1}".format("world", "test"));
Using Tagged Template Literals:
Tagged template literals offer an alternative method. However, it's important to note that substitutions are still evaluated without allowing for interpolation of identifiers like "p0".
function formatter(literals, ...substitutions) { return { format: function() { var out = []; for(var i=0, k=0; i < literals.length; i++) { out[k++] = literals[i]; out[k++] = arguments[substitutions[i]]; } out[k] = literals[i]; return out.join(""); } }; } console.log(formatter`Hello, <pre class="brush:php;toolbar:false">console.log(`Hello, ${"world"}. This is a ${"test"}`);. This is a `.format("world", "test"));
Avoiding Deferral:
Consider using template strings as intended without any format function or deferral. Template strings provide a concise and efficient way to interpolate dynamic values without additional complexity.
The above is the detailed content of How to Defer ES6 Template Literal Evaluation?. For more information, please follow other related articles on the PHP Chinese website!