2014-04-11 75 views
0

我正在使用Handlebars作爲我的模板。有沒有一種方法可以使用幫助器正在使用的模板中的值?從模板中獲取值在車把手幫手

重要的是給定的值是一個字符串,後來是值。

例子:

// Template.html 
<p>{{myHelper 'This is an awsome {name}'}}</p> 

Helper.js 
Handlebars.registerHelper('myHelper', function(string){ 

// string is 'This is an awsome {name}' AND it is important that {name} is a string and at this point not the real value 

var myNewString = string.replace(\{name}\, Handlebars.getValueByKey(name)); 
return myNewString 

}); 

如果是「測試」的返回值將是這是一個要命的測試

name的值在另一個助手給出了這個模板,其中將「name」定義爲「Test」作爲字符串。

我要尋找一個功能類似於我在我的例子中使用 - getValueByKey

有沒有做到這一點的典型方式是什麼?在官方文檔中我沒有找到類似的東西。

編輯:我很抱歉 - 我不知道爲什麼在代碼框中的例子看起來像這樣。

+0

why getValueByKey?你只是想返回你傳遞的任何價值的長度? – ckross01

+0

這只是一個例子 - 我真正的handlebars-helper不返回字符串的長度,但需要獲取模板中返回的字符串的值 – TJR

回答

0

通常,您只需設置一個通用幫助程序,該幫助程序將返回您需要的任何值。但是你需要在助手中傳遞你想要的值。如果您需要多個參數,只需傳入額外的值即可。例如,

<p>My name is {{name}}</p> 
<p>My Phone number is {{phonenumber}}</p> 
<p>My Address is {{address}}</p> 
<p>The length of all three are {{stringLength name phonenumber address}}</p> 

Handlebars.registerHelper('stringLength', function(name, phonenumber, address) { 
    var retVal = name + phonenumber + address; 
    return new Handlebars.SafeString(retVal.length); 
}); 
+0

我的例子很糟糕 - 對不起。重要的是我只給了一個字符串。一個更好的例子是:{{myHelper'我的名字是{name}'}}重要的是我的幫手得到字符串「我的名字是{name}」,然後從助手中的「name」不是之前。 – TJR

+0

我編輯了一下這個例子。也許現在清楚我正在尋找什麼樣的解決方案。 – TJR

1

你很近。關鍵在於準確傳遞您想要的模板:

// Template.html 
<p>{{myHelper 'This is an awesome' name}}</p> 

Helper.js 
Handlebars.registerHelper('myHelper', function(string, name){ 

    // string is 'This is an awesome' 
    // value of {name} is passed as another value 
    // If you wanted to do other things with the {name} you could 
    // do that in the function below 

    var myNewString = string + name; 
    return myNewString 

}); 

希望這與您所尋找的更接近。