从JsRender调用JavaScript函数 [英] Call JavaScript function from JsRender
问题描述
我有一个JsRender模板。当模板渲染时,我想调用一个JavaScript函数来操作一些数据。
I have a JsRender template. When template is rendering I want to call a JavaScript function to manipulate some data.
这是我的JsRender模板。
Here is my JsRender template.
<tr class="template-download">
<td class="size">
<span>{{:size}}</span>
</td>
</tr>
现在我要传递:size
value到JavaScript函数并获取返回值。所以我可以显示返回值而不是:size
value。
Now I want to pass :size
value to JavaScript function and get the return value. So I can show return value instead of :size
value.
我的JavaScript函数是
My JavaScript function is
function getSize(size) {
var megabytes = size / (1024 * 1024);
return megabytes.toFixed(2) + "MB";
}
我该怎么做?
推荐答案
您可以使用辅助函数来完成此操作。当你调用render时,你可以定义一个辅助函数'并'传递给你的模板:
You can do this by using a helper function. When you call render, you can define and pass a helper function 'into' your template:
$("#tmpl").render(data, {
getSize: function(size) {
var megabytes = size / (1024 * 1024);
return megabytes.toFixed(2) + "MB";
}
});
然后,在你的模板中,你可以调用这样的帮助函数:
Then, in your template, you call the helper function like this:
<tr class="template-download">
<td class="size">
<span>{{:size}} {{:~getSize(size)}} </span>
</td>
</tr>
我对你的模板的使用方式做了一些假设,但这应该可以帮到你去。
I've made a couple of assumptions about how your template is being used, but this should get you going.
这文章有一个与辅助函数相关的部分,@ BorisMoore在他的 jsViews上有很多很好的例子。网站。
This article has a section related to helper functions, and @BorisMoore has a number of good examples on his jsViews site.
这篇关于从JsRender调用JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!