grunt.template

2018-11-02 14:04 更新

grunt.template

可以手工調(diào)用模板函數(shù)處理模版字符串。另外,config.get 方法(被很多任務(wù)所使用)會(huì)自動(dòng)解析 <% %>類型的模版字符串,此類型的模版字符串是在 Gruntfile 中指的配置數(shù)據(jù)中定義的。

grunt.template.process

處理一個(gè) Lo-Dash 模版 字符串。template 參數(shù)將被遞歸處理,知道沒有任何模版位置。

默認(rèn)的數(shù)據(jù)對(duì)象是整個(gè)配置對(duì)象,但是,如果設(shè)置了options.data,則使用該對(duì)象。默認(rèn)的模板分隔符是<% %>,但是,如果options.delimiters被設(shè)置為自定義的形式(通過(guò)grunt.template.addDelimiters 進(jìn)行設(shè)置),那么后續(xù)就會(huì)使用此模板分隔符。

grunt.template.process(template [, options])

在模板內(nèi)部暴露了grunt對(duì)象,因此你可以這樣做<%= grunt.template.tody('yyyy') %>。注意, 如果數(shù)據(jù)對(duì)象已經(jīng)有了grunt屬性,那么在模板內(nèi)部將無(wú)法訪問(wèn)grunt API。

在下面這個(gè)案例中,baz 屬性被遞歸處理,直到再也沒有多余的 <% %> 模版需要處理。

var obj = {
  foo: 'c',
  bar: 'b<%= foo %>d',
  baz: 'a<%= bar %>e'
};
grunt.template.process('<%= baz %>', {data: obj}) // 'abcde'

grunt.template.setDelimiters

設(shè)置Lo-Dash模板的分隔符為預(yù)定義的形式,以防需要手動(dòng)調(diào)用grunt.util._.template。config分隔符默認(rèn)是<% %>。

你可能永遠(yuǎn)不會(huì)使用這個(gè)方法,因?yàn)槟闼褂玫?nbsp;grunt.template.process 在內(nèi)部使用的就是這個(gè)方法。

grunt.template.setDelimiters(name)

grunt.template.addDelimiters

Lo-Dash模板添加一個(gè)命名分隔符。你或許不需要使用這個(gè)方法,因?yàn)閮?nèi)置的分割符應(yīng)該足以滿足需求了,但是你仍可以隨時(shí)添加{% %} 或者[% %]風(fēng)格的分隔符。

name 參數(shù)應(yīng)當(dāng)是唯一的,因?yàn)檫@也是我們通過(guò) grunt.template.setDelimiters 獲取分隔符的方式,并且后續(xù)作為 grunt.template.process 的一個(gè)選項(xiàng)來(lái)使用。

grunt.template.addDelimiters(name, opener, closer)

在此實(shí)例中,如果我們希望使用 {% %} 形式的分隔符,我們需要如下這樣設(shè)置:

grunt.template.addDelimiters('myDelimiters', '{%', '%}')

助手函數(shù)

grunt.template.date

使用dateformat library格式化一個(gè)日期。

grunt.template.date(date, format)

在這個(gè)案例中,指定的日期被格式化為 month/day/year。

grunt.template.date(847602000000, 'yyyy-mm-dd') // '1996-11-10'

grunt.template.today

使用 dateformat library格式化當(dāng)前日期。

grunt.template.today(format)

在這個(gè)案例中,當(dāng)前日期被格式化為4位數(shù)字表示的年份。

grunt.template.today('yyyy') // '2014'
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)