鍍金池/ 問(wèn)答/Linux  數(shù)據(jù)庫(kù)  HTML/ 一個(gè)關(guān)于 ES 6 字符串模板的問(wèn)題,使用webpack 轉(zhuǎn)化失效。

一個(gè)關(guān)于 ES 6 字符串模板的問(wèn)題,使用webpack 轉(zhuǎn)化失效。

我將某些獨(dú)立的html結(jié)構(gòu)抽出來(lái)當(dāng)做tpl文件:

<div id="demo">
  <div class="part-a">
    ${content.partA}
    <div class="part-b">
      ${content.partB}
      <div class="part-c">${content.partC}</div>
    </div>
  </div>
</div>

然后在 js 中這樣寫:

import tpl from './src/test.tpl';

const html = content => `${tpl}`;

let content = {
  partA: 'a',
  partB: 'b',
  partC: 'c'
};

console.log(html(content));

但是輸出的結(jié)果是這樣:

clipboard.png

請(qǐng)問(wèn)如何才能將里面的變量替換?

回答
編輯回答
凝雅

因?yàn)榉匆?hào)模板插值只會(huì)翻譯一次。

const html = content => `${tpl}`;

// 等價(jià)于
const html = content => "" + tpl ""; 

// 你需要在運(yùn)行時(shí)對(duì) tpl 再次進(jìn)行模板插值,只考慮實(shí)現(xiàn)功能的話,可以這樣:
const html = content => eval("`" + tpl "`"); 
2018年3月22日 12:47
編輯回答
假灑脫

概念要搞清楚,模板字符串是屬于javascript的,不是html的,不能用在html上,你的問(wèn)題如果不用第三方的模板引擎的話只能手動(dòng)去操作DOM把你的html字符串拼接到頁(yè)面上,相關(guān)的api有innerHTML,appendChild

2017年12月14日 19:44
編輯回答
好難瘦
function format (template, data) {
    var keys = Object.keys(data),
        dataList;
    dataList = keys.map(function (key) {
        return data[key];
    });
    // 這里使用反引號(hào)來(lái)構(gòu)建模板引擎
    return new Function (keys.join(','), 'return `' + template + '`;')
        .apply(null, dataList);
}
    import tpl from './src/test.tpl';


let content = {
  partA: 'a',
  partB: 'b',
  partC: 'c'
};

    let re= format(tpl ,content );
2017年11月9日 22:55