可以使用Grunt提供的模板相關(guān)函數(shù)來(lái)手動(dòng)的處理模板字符串。此外,config.get
方法(許多任務(wù)都有用到這個(gè)方法)可以自動(dòng)解析指定在Gruntfile
中作為配置數(shù)據(jù)的<% %>
風(fēng)格的模板字符串。
處理Lo-Dash模板字符串。template
參數(shù)會(huì)以遞歸的方式進(jìn)行處理,直到不再有需要處理的模板。
默認(rèn)情況下數(shù)據(jù)對(duì)象就是項(xiàng)目完整的配置對(duì)象,但是如果設(shè)置了options.data
,就會(huì)使用這個(gè)options.data
中指定的數(shù)據(jù),而不會(huì)使用項(xiàng)目完整的配置對(duì)象。默認(rèn)的模板分隔符是<% %>
,但是如果將options.delimiters
設(shè)置為自定義的分隔符,模板就會(huì)使用自定義的分隔符替換默認(rèn)分隔符。
grunt.template.process(template [,options])
在模板內(nèi)部,grunt
對(duì)象是暴露的,因此你可以這樣做<%= grunt.template.tody('yyyy') %>
。注意,如果數(shù)據(jù)對(duì)象也有一個(gè)名為grunt
的屬性,那么在模板里面就無(wú)法使用grunt
系列的API。
這里有一個(gè)例子,Grunt會(huì)以遞歸的方式處理到baz
屬性中的模板,知道不再有<% %>
風(fēng)格的模板需要處理。
var obj = {
foo: 'c',
bar: 'b<%= foo %>d',
baz: 'a<%= bar %>e'
};
grunt.template.process('<%= baz %>', {data: obj}) // 'abcde'
設(shè)置Lo-Dash模板分隔符為預(yù)定義的分隔符,以防你需要手動(dòng)的調(diào)用grunt.util._.template
方法來(lái)進(jìn)行處理。默認(rèn)情況下config
中會(huì)使用<% %>
風(fēng)格的分隔符。
你或許無(wú)需使用這個(gè)方法,因?yàn)槟闼褂玫?code>grunt.template.process方法會(huì)在內(nèi)部使用這個(gè)方法進(jìn)行處理。
grunt.template.setDelimiters(name)
給Lo-Dash模板添加一組命名分隔符。你或許無(wú)需使用這個(gè)方法,因?yàn)閮?nèi)置的分割符應(yīng)該足以滿足你的需求,但是你也可以隨時(shí)添加<% %>
或者[% %]
風(fēng)格的分隔符。
grunt.template.addDelimiters(name, opener, closer)
使用dateformat庫(kù)格式化一個(gè)日期。
grunt.template.date(date, format)
這里有一個(gè)例子,指定的日期將被格式化為年-月-日的形式。
grunt.template.date(847602000000, 'yyyy-mm-dd') // '1996-11-10'
使用dateformat庫(kù)格式化當(dāng)前日期。
grunt.template.today(format)
這里有一個(gè)例子,當(dāng)前日期會(huì)被格式化為一個(gè)用4位數(shù)字表示年份的格式。
grunt.template.today('yyyy') //'2014'
(有人提醒我每年都更新一下日期相關(guān)的信息,因此在文檔只會(huì)出現(xiàn)當(dāng)前年份的日期信息)。