Deferring Execution for ES6 Template Literals
ES6 Template Literals provide a powerful syntactic sugar for string interpolation, but what if you want to defer evaluation until after dynamic element creation?
The Issue
Traditionally, using String.prototype.format would allow deferred evaluation. However, template literals are evaluated at parse time, preventing this approach.
Solution 1: Use Tagged Template Literals
Tagged template literals allow you to intercept and process the template literal before evaluation:
function formatter(literals, ...substitutions) { return { format: function() { // ... code here ... } }; } console.log(formatter`Hello, <pre class="brush:php;toolbar:false">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"));
Solution 2: Use Plain String Literals
Alternatively, you can use plain string literals and manually parse the substitutions:
const welcome = (p0, p1) => `Hello, ${p0}. This is a ${p1}`; console.log(welcome("world", "test"));
Solution 3: Avoid Template Literals and Use Function Parameters
Finally, you can avoid template literals altogether and use function parameters:
Considerations
The above is the detailed content of How to Defer Evaluation of ES6 Template Literals?. For more information, please follow other related articles on the PHP Chinese website!