如何在javascript微模板中将变量传递给模板?

时间:2014-09-03 11:44:34

标签: javascript

John Resig写了一个简单的javascript模板引擎。 (下面的完整代码)

他提供了一个带循环的示例模板:

<script type="text/html" id="user_tmpl">
  <% for ( var i = 0; i < users.length; i++ ) { %>
    <li><a href="<%=users[i].url%>"><%=users[i].name%></a></li>
  <% } %>
</script>

我有succsfulle称为模板,如下:

$.getJSON('/data/list.json', function(data){
    //console.log(data)
    $('.container')[0].innerHTML = tmpl("item_tmpl", data);
})

我不明白的是我在哪里设置模板使用的变量。这是我使用的json:

[
    {
        "id": 1,
        "name": "Skateboard",
        "price": 1299,
        "currency": "SEK",
        "thumbnail": "/static/img/products/1-t.jpg"
    },

    {
        "id": 2,
        "name": "Ball",
        "price": 145,
        "currency": "SEK",
        "thumbnail": "/static/img/products/2-t.jpg"
    },

    {
        "id": 3,
        "name": "Dog Shampoo",
        "price": 69,
        "currency": "SEK",
        "thumbnail": "/static/img/products/3-t.jpg"
    },

    {
        "id": 4,
        "name": "A trip to the sun with Erik",
        "price": 29000,
        "currency": "SEK",
        "thumbnail": "/static/img/products/4-t.jpg"
    }
]

这是完整的引擎:

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
  var cache = {};

  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :

      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +

        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +

        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");

    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();

1 个答案:

答案 0 :(得分:0)

我需要将它定义为我传递给模板的对象内的对象,如下所示:

var dataObject = { productsData: data };