當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Lodash _.template()用法及代碼示例

Lodash是一個JavaScript庫,可在underscore.js之上運行。 Lodash幫助處理數組,字符串,對象,數字等。

_.template()方法用於創建一個模板函數,該函數已編譯並可以在插值定界符中插值數據的屬性,在評估定界符中執行JavaScript,並在轉義定界符中執行HTML-escape數據的插值屬性。此外,數據屬性作為自由變量在模板中檢索。

用法:

_.template( string, options )

參數: 此方法接受上麵提到和下麵描述的兩個參數:

  • string:它是將用作模板的字符串。它是一個可選值。
  • options:它是可用於修改方法行為的對象。它是一個可選值。

選項字段具有以下可選參數:



  • options.interpolate:它是一個正則表達式,用於指定HTML插值定界符。
  • options.evaluate:它是一個正則表達式,用於指定HTML評估分隔符。
  • options.escape:這是一個指定HTML轉義分隔符的正則表達式。
  • options.imports:它是一個對象,將作為自由變量導入到模板中。
  • options.sourceURL:它是一個字符串,表示已編譯模板的源URL。
  • options.variable:它是一個字符串,表示數據對象的變量名稱。

返回值:此方法返回已編譯的模板函數。

範例1:

Javascript

// Requiring lodash library 
const _ = require('lodash'); 
  
// Using the _.template() method to 
// create a compiled template using  
// the "interpolate" delimiter 
var comptempl = 
  _.template('Hi <%= author%>!'); 
  
// Assigning the value to the   
// interpolate delimiter 
let result = 
  comptempl({ 'author':'Nidhi' }); 
  
// Displays output 
console.log(result);

輸出:

Hi Nidhi!

範例2:

Javascript

// Requiring lodash library 
const _ = require('lodash'); 
  
// Using the _.template() method to  
// create a compiled template using  
// the internal print function in 
// the "evaluate" delimiter 
var comptempl = _.template( 
  '<% print("hey " + geek); %>...'
); 
  
// Assigning value to the evaluate delimiter 
let result = 
  comptempl({ 'geek':'Nisha' }); 
  
// Displays output 
console.log(result);

輸出:

hey Nisha...

範例3:forEach()方法用作評估定界符,以便生成HTML作為輸出。

Javascript

// Requiring lodash library 
const _ = require("lodash"); 
  
// Using the template() method with 
// additional parameters 
let compiled_temp = _.template( 
  "<% _.forEach(students, function(students) " + 
    "{ %><li><b><%- students %></b></li><% }); %>"
)({ students:["Rahul", "Rohit"] }); 
  
// Displays the output 
console.log(compiled_temp);

輸出:

<li><b>Rahul</b></li><li><b>Rohit</b></li>

相關用法


注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Lodash _.template() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。