[英]Call JavaScript function from JsRender
I have a JsRender template. 我有一个JsRender模板。 When template is rendering I want to call a JavaScript function to manipulate some data.
当模板渲染时,我想调用JavaScript函数来操作一些数据。
Here is my JsRender template. 这是我的JsRender模板。
<tr class="template-download">
<td class="size">
<span>{{:size}}</span>
</td>
</tr>
Now I want to pass :size
value to JavaScript function and get the return value. 现在我想将
:size
值传递给JavaScript函数并获取返回值。 So I can show return value instead of :size
value. 所以我可以显示返回值而不是
:size
value。
My JavaScript function is 我的JavaScript功能是
function getSize(size) {
var megabytes = size / (1024 * 1024);
return megabytes.toFixed(2) + "MB";
}
How can I do this? 我怎样才能做到这一点?
You can do this by using a helper function. 您可以使用辅助函数来完成此操作。 When you call render, you can define and pass a helper function 'into' your template:
当您调用render时,您可以定义辅助函数并将其传递到模板中:
$("#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. 我对你的模板的使用方式做了一些假设,但这应该让你顺利。
This article has a section related to helper functions, and @BorisMoore has a number of good examples on his jsViews site . 本文有一个与辅助函数相关的部分,@ BorisMoore在他的jsViews站点上有很多很好的例子。
I believe you must use helper functions. 我相信你必须使用辅助功能。 See the two references below.
请参阅下面的两个参考。 The 2nd is a fully flushed out example.
第二个是一个完全刷新的例子。
http://borismoore.github.io/jsrender/demos/step-by-step/09_helper-functions.html http://borismoore.github.io/jsrender/demos/step-by-step/09_helper-functions.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.