阅读量:155
要使用Lodash的模板功能,首先需要引入Lodash库。然后可以使用_.template()方法来编译模板字符串。以下是一个简单的示例:
// 引入Lodash库
const _ = require('lodash');
// 定义模板字符串
const templateString = '<%= name %>';
// 编译模板字符串
const compiledTemplate = _.template(templateString);
// 定义模板数据
const data = { name: 'John' };
// 渲染模板
const renderedTemplate = compiledTemplate(data);
console.log(renderedTemplate); // 输出:John
上面的例子中,我们定义了一个模板字符串,然后使用<%= name %>_.template()方法编译这个模板字符串。接着定义了一个包含数据的对象{ name: 'John' },最后通过compiledTemplate(data)来渲染模板并输出结果。