简体   繁体   English

ES6 的标记模板文字的 ES5 替代方案是什么?

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

I have the following code in ES6 standard:我在 ES6 标准中有以下代码:

 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: Output:

 <h1>Hello Arcanadian Arc!</h1>

As, it's a ES6 standard code, IE doesn't support it.因为它是 ES6 标准代码,IE 不支持它。 So, I decided to transpile this to ES5 using Babel and that's what I did.因此,我决定使用 Babel 将其转换为 ES5,这就是我所做的。 But I am not satisfied with the output.但我对 output 并不满意。 Here is the output:这是 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:我想通过将 ES6 的 ${} 替换为 {{ }} 或其他名称来调用它,然后它看起来像这样:

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

Output: Output:

<h1>Hello Arcanadian Arc!</h1>

It looks pretty like ES6 and the main thing, it is not messy like the earlier one.它看起来很像 ES6,主要的是,它不像早期的那样凌乱。 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?这可以用作 ES6 的替代品吗? Or is there a pollyfill for it ?还是有一个pollyfill呢?

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您可以在 regex 和 replace 的帮助下执行此类操作,但您应该在开发项目时使用最新功能,将这些怪癖留给babel或任何其他转译器等工具

 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}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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