Are there any polyfills for javascript template strings that use a backtick? I'm referring to code that looks like this:
var textTemplate = `
<h1>My Template String</h1>
<p>Some more stuf here...</p>
`;
I do not wish to use a transpiler such as babel or any other tools that require a build step. Additionally, javascript template engines that place the template inside of a separate script tag are not ideal for me either.
I'd really just like to be able to use template strings alongside otherwise standard ES5 code in the same file. Is this possible?
EDIT: I specifically need template strings to work in IE11. I realize they already do in most other browsers. I'm also now aware that polyfill isn't the correct terminology for what I am wanting.
Template literals are enclosed by backtick ( ` ) characters instead of double or single quotes. Along with having normal strings, template literals can also contain other parts called placeholders, which are embedded expressions delimited by a dollar sign and curly braces: ${expression} .
Backticks are an ES6 feature that allows you to create strings in JavaScript. Although backticks are mostly used for HTML or code embedding purposes, they also act similar to single and double quotes. Besides, using backticks makes it easier for string operations.
String interpolation in JavaScript is a process in which an expression is inserted or placed in the string. To insert or embed this expression into the string a template literal is used. By using string interpolation in JavaScript, values like variables and mathematical expressions and calculations can also be added.
If you look at the ECMAScript 6 compatibility table, you'll see that template literals are not supported by IE11.
Are there any polyfills for javascript template strings that use a backtick?
No. You can't have a polyfill for new Javascript syntax which the backticks are. A polyfill can't affect the compiling of the code or the execution of a line of code. It can only affect functions calls at run time.
The solution for new Javascript syntax is to transpile from the new syntax to ES5 compatible code.
You can't even create a function that would do the same type of string substitution (when passed a normal Javascript quoted string) because the function implementation would not have access to the locally scoped variables that are typically used in backtick templates.
There are other types of string substitution that can be implemented in a function, but you have to pass the values that you want substituted in (like sprintf in C and use a different syntax than the template literals) rather than just use variable names in the template string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With