Search code examples
javascriptjqueryjsviews

JsViews doesn't seem to work with numeric properties


When I try to pass JavaScript object with numeric properties

{ 1: "One", 2: "Two", 3: "Three" }

Data-binding doesn't render property values, only numbers like in example

$.templates("template", "#template");
$.link.template("#row", { 1: "One", 2: "Two", 3: "Three" });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsviews/0.9.90/jsviews.min.js"></script>

<script id="template" type="text/x-jsrender">
  <td>{{:1}}</td>
  <td>{{:2}}</td>
  <td>{{:3}}</td>
</script>

<table>
  <tr id="row">
  </tr>
</table>

But if I change property names of object to something beginning with letter it works OK

$.templates("template", "#template");
$.link.template("#row", { n1: "One", n2: "Two", n3: "Three" });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsviews/0.9.90/jsviews.min.js"></script>

<script id="template" type="text/x-jsrender">
  <td>{{:n1}}</td>
  <td>{{:n2}}</td>
  <td>{{:n3}}</td>
</script>

<table>
  <tr id="row">
  </tr>
</table>

Is it bug or feature? How to make jsViews work with numeric properties without converting passed object?


Solution

  • If you write {{:4}} for some integer, then JsRender treats that as an expression, and evaluates it. (For example {{:4*12+2}} will render 50).

    In JavaScript if an object property name (key) is not a valid identifier name you have to use the square bracket accessor syntax.

    In JsRender/JsViews templates, the same is true. (See www.jsviews.com/#paths).

    Here are multiple examples:

    $.templates("template", "#template");
    $.link.template("#row",
     { 1: "One", "2": "Two", 3: "Three", other: { 50: "fifty" }, 4: { 5: "five"}, "a b": "AB" });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jsviews/0.9.90/jsviews.min.js"></script>
    
    <script id="template" type="text/x-jsrender">
      <td>{{:#data[1]}}</td>
      <td>{{:#data[1+1]}}</td>
      <td>{{:#data["3"]}}</td>
      <td>{{:other[50]}}</td>
      <td>{{:~root[1]}}</td>
      <td>{{:#data[4]["5"]}}</td>
      <td>{{:#data["a b"]}}</td>
    </script>
    
    <table>
      <tr id="row">
      </tr>
    </table>