JavaScript 用户定义的对象模板文字格式

JavaScript user defined template literal formatting from object

我想允许用户定义一个从对象插入的模板。例如,我有对象:

const desc = {
    reagent: 'NaOH',
    mass: '25.6g',
};

我希望用户能够定义自己的格式字符串,例如'${mass} of ${reagent}',这样我就可以调用一些format(formatStr, desc)来获得'25.6g of NaOH'

这种行为是内置的吗?

只要插入字段 XY 并且不在其中进行计算,构建起来相当简单:

const desc = {
    reagent: 'NaOH',
    mass: '25.6g',
};

const formatStr = '${mass} of ${reagent}';

function format(tpl, args){
  return tpl.replace(/$\{[^\}]+\}/g, (m) => args[m.slice(2, -1).trim()]);
}

console.log(format(formatStr, desc));

如果您想解析这些占位符并在其中进行计算,我们将进入 evil() 领域。

如果您不介意使用知名的实用程序库,那么 Lodash 内置了一个非常全面的模板引擎。

https://lodash.com/docs/4.17.15#template

摘自他们的文档:

// Use the "interpolate" delimiter to create a compiled template.
var compiled = _.template('hello <%= user %>!');
compiled({ 'user': 'fred' });

// => 'hello fred!'

// Use the ES template literal delimiter as an "interpolate" delimiter.
var compiled = _.template('hello ${ user }!');
compiled({ 'user': 'pebbles' });

// => 'hello pebbles!'

您还可以指定自己的自定义分隔符:

// Use custom template delimiters.
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
var compiled = _.template('hello {{ user }}!');
compiled({ 'user': 'mustache' });

// => 'hello mustache!'

如果包大小是一个问题,你可以选择只安装来自 Lodash 的 template 方法: https://www.npmjs.com/package/lodash.template