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') // This returns a year in format such as '2020'