簡體   English   中英

如何在javascript微型模板中將變量傳遞到模板?

[英]How do I pass variables to the template in javascript micro templating?

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>

我已經成功調用了模板,如下所示:

$.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;
  };
})();

我需要將其定義為傳遞給模板的對象內部的對象,如下所示:

var dataObject = { productsData: data };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM