简体   繁体   中英

What is the ES5 alternative of ES6's tagged template literals?

I have the following code in ES6 standard:

 function test(html, ...args) {
   return html.slice(1).reduce((str, elem, i) => str + args[i] + 
  elem, html[0]);
 }

And this to use it:

 var hello = 'Hello';
 var world = 'Arcanadian Arc';
 document.body.innerHTML = test`<h1>${hello} ${world}!</h1>`;

Output:

 <h1>Hello Arcanadian Arc!</h1>

As, it's a ES6 standard code, IE doesn't support it. So, I decided to transpile this to ES5 using Babel and that's what I did. But I am not satisfied with the output. Here is the output:

function _templateObject() {
   var data = _taggedTemplateLiteral(["<h1>", " I am very happy </h1>"]);

    _templateObject = function _templateObject() {
     return data;
  };

   return data;
 }

  function _taggedTemplateLiteral(strings, raw) { if (!raw) { 
   raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }

 function test(html) {
   for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
     args[_key - 1] = arguments[_key];
   }

   return html.slice(1).reduce(function (str, elem, i) {
     return str + args[i] + elem;
   }, html[0]);
}

And to use it:

 var hello = 'Hello';
 var world = 'Arcanadian Arc';
 document.body.innerHTML = test(_templateObject(), hello);

It works but its syntax is a bit messy. I wanted to call this something like this by replacing ES6's ${} with a {{ }} or aome other, then it would look like this:

var hello = "Hello";
var world = "Arcanadian Arc";
document.body.innerHTML = test`<h1>{{ hello }} {{ world }}!';

Output:

<h1>Hello Arcanadian Arc!</h1>

It looks pretty like ES6 and the main thing, it is not messy like the earlier one. But I don't know how to do that? Can you help me, But the question is? can this be done? Can this be used as an ES6 one's alternative? Or is there a pollyfill for it ?

Thanks In Advance

You can do something as such with help of regex and replace, but you should be using the latest feature while developing the project leave these quirks for tools like babel or any other transpiler

 var hello = "Hello"; var world = "Arcanadian Arc"; function test(str,args){ return str.replace(/{{(.*?)}}/g, (m,g1)=> args[g1.trim()] || m) } console.log(test('<h1>{{ hello }} {{ world }},</h1>',{hello,world}))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM