MmD
MmD

Reputation: 2154

call function in underscore template

I want use one function in my template underscore. my function created in my .javascript file like this:

<script type="text/javascript">
   function en2per(str){
      str = typeof(str) == "number" ? str.toString() : str;
      var output = '';
      var num = 1728;
      for (var i = 0, len = str.length; i < len; i++) {
        if(str.charCodeAt(i)>=48 && str.charCodeAt(i)<=57)
          output += String.fromCharCode(str.charCodeAt(i)+num);
        else
          output += str[i];
        }
    return output;
    };

    var order_temp = _.template($("#order_template").html());
    var order_json = {orders:data.orders};
    $('#full .pages').append(order_temp(order_json));
</script>

and this is my templete underscore :

<script type="text/template" id="order_template">
   <ul class="item_list">
   <% _.each(orders,function(item){%>
     <li class="cells">
       <div class="part number">
          <span class="spans"><%= en2per(item.counter)%></%> // I get error this place...
       </div>
     </li>
   <% });%>
   </ul>
</script>

when run my code I got error ... in my template underscore this function en2per() not found!!! Now I want call this function in my template.

Upvotes: 0

Views: 352

Answers (1)

bowheart
bowheart

Reputation: 4676

The order of your execution is:

1) The en2per function and the underscore template need to be declared (any order should work)

2) The jQuery needs to use the template

3) The underscore template needs to use the en2per function

This is all solved by making sure the en2per function is not in a $(document).ready() handler, and making sure the jQuery using the template (so the template will need to have been loaded) is:

<script type="text/template" id="order_template">
    ....
</script>

<script>
    function en2per(str) {
        ....
    }

    $(document).ready(function() {
        var order_temp = _.template($("#order_template").html());
        var order_json = {orders:data.orders};
        $('#full .pages').append(order_temp(order_json));
    });
</script>

Here's a JSFiddle

Upvotes: 2

Related Questions