Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
来自对象的JavaScript用户定义模板文字格式_Javascript_Typescript_Template Literals - Fatal编程技术网

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

来自对象的JavaScript用户定义模板文字格式,javascript,typescript,template-literals,Javascript,Typescript,Template Literals,我想允许用户定义一个从对象插值的模板。例如,我有一个对象: const desc={ 试剂:“NaOH”, 质量:'25.6g', }; 我希望用户能够定义他们自己的格式字符串,例如'${reagent}'的${mass},这样我可以调用一些格式(formatStr,desc)来获得'25.6g NaOH' 这种类型的行为是内置的吗?只要它只是插入字段XY而没有计算,构建起来就相当简单: const desc={ 试剂:“NaOH”, 质量:'25.6g', }; 常量formatStr=$

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

const desc={
试剂:“NaOH”,
质量:'25.6g',
};
我希望用户能够定义他们自己的格式字符串,例如
'${reagent}'的${mass}
,这样我可以调用一些
格式(formatStr,desc)
来获得
'25.6g NaOH'


这种类型的行为是内置的吗?

只要它只是插入字段XY而没有计算,构建起来就相当简单:

const desc={
试剂:“NaOH”,
质量:'25.6g',
};
常量formatStr=${试剂}的${mass};
函数格式(tpl、args){
返回tpl.replace(/\$\{[^\}]+\}/g,(m)=>args[m.slice(2,-1.trim());
}

log(格式(formatStr,desc))只要它只是插入字段XY而不进行计算,构建起来就相当简单:

const desc={
试剂:“NaOH”,
质量:'25.6g',
};
常量formatStr=${试剂}的${mass};
函数格式(tpl、args){
返回tpl.replace(/\$\{[^\}]+\}/g,(m)=>args[m.slice(2,-1.trim());
}

log(格式(formatStr,desc))如果您不介意使用著名的实用程序库,那么它内置了一个非常全面的模板引擎

摘自他们的文件:

// 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!'
如果捆绑大小是一个问题,您可以选择仅安装Lodash的
模板
方法:

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

摘自他们的文件:

// 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!'
如果捆绑大小是一个问题,您可以选择仅安装Lodash的
模板
方法:

我认为这是不可能的。您可能需要接受用户定义的模板文本,并使用适当的值执行替换。如果您提取模板名称YUP键/值对swao键,并将字符串中的值替换为${}of valueLook at,这应该是非常简单的,这是ECMAScript中模板文字添加的一部分。我认为这不可能是现成的。您可能需要接受用户定义的模板文本,并使用适当的值执行替换。如果您提取模板名称YUP键/值对swao键,并使用字符串替换${}的valueLook-at作为模板文本添加到ECMAScript的一部分,那么这应该非常简单。