grunt.template
可以使用提供的模板函数手动处理模板字符串。此外,config.get
方法(被许多任务使用)会自动展开在 Gruntfile
中指定为配置数据的 <% %>
风格的模板字符串。
grunt.template.process
处理 Lo-Dash 模板 字符串。template
参数将被递归处理,直到没有更多的模板需要处理。
默认数据对象是整个配置对象,但如果设置了 options.data
,则将使用该对象。默认模板分隔符是 <% %>
,但如果将 options.delimiters
设置为自定义分隔符名称(使用 grunt.template.addDelimiters
设置),则将使用这些模板分隔符。
grunt.template.process(template [, options])
在模板内部,grunt
对象是公开的,因此您可以执行诸如 <%= grunt.template.today('yyyy') %>
之类的操作。注意,如果数据对象已经有 grunt
属性,则在模板中将无法访问 Grunt API。
在此示例中,baz
属性被递归处理,直到没有更多的 <% %>
模板需要处理。
var obj = {
foo: 'c',
bar: 'b<%= foo %>d',
baz: 'a<%= bar %>e'
};
grunt.template.process('<%= baz %>', {data: obj}) // 'abcde'
grunt.template.setDelimiters
设置 Lo-Dash 模板 分隔符为预定义集,以防需要手动调用 grunt.util._.template
。默认包含 config
分隔符 <% %>
。
您可能不需要使用此方法,因为您将使用 grunt.template.process
,它在内部使用此方法。
grunt.template.setDelimiters(name)
grunt.template.addDelimiters
添加一组命名的 Lo-Dash 模板 分隔符。您可能不需要使用此方法,因为内置的分隔符应该已经足够,但您可以随时添加 {% %}
或 [% %]
风格的分隔符。
name
参数应该是唯一的,因为这是我们从 grunt.template.setDelimiters
访问分隔符以及作为 grunt.template.process
选项的方式。
grunt.template.addDelimiters(name, opener, closer)
在此示例中,如果我们要使用上面提到的 {% %}
风格,我们将使用以下代码:
grunt.template.addDelimiters('myDelimiters', '{%', '%}')
帮助程序
grunt.template.date
使用 dateformat 库 格式化日期。
grunt.template.date(date, format)
在此示例中,特定日期被格式化为月/日/年。
grunt.template.date(847602000000, 'yyyy-mm-dd') // '1996-11-10'
grunt.template.today
使用 dateformat 库 格式化今天的日期。
grunt.template.today(format)
在此示例中,今天的日期被格式化为 4 位数年份。
grunt.template.today('yyyy') // 这将返回类似 '2020' 的年份