最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Call JavaScript function from JsRender - Stack Overflow

programmeradmin2浏览0评论

I have a JsRender template. When template is rendering I want to call a JavaScript function to manipulate some data.

Here is my JsRender template.

<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. So I can show return value instead of :size value.

My JavaScript function is

function getSize(size) {
    var megabytes = size / (1024 * 1024);
    return megabytes.toFixed(2) + "MB";
}

How can I do this?

I have a JsRender template. When template is rendering I want to call a JavaScript function to manipulate some data.

Here is my JsRender template.

<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. So I can show return value instead of :size value.

My JavaScript function is

function getSize(size) {
    var megabytes = size / (1024 * 1024);
    return megabytes.toFixed(2) + "MB";
}

How can I do this?

Share Improve this question edited May 16, 2018 at 19:26 Vadim Ovchinnikov 14k7 gold badges65 silver badges94 bronze badges asked Jan 6, 2014 at 10:41 cp100cp100 1,4936 gold badges20 silver badges36 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 18

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.

This article has a section related to helper functions, and @BorisMoore has a number of good examples on his jsViews site.

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

发布评论

评论列表(0)

  1. 暂无评论