代码之家  ›  专栏  ›  技术社区  ›  MandoMando

有没有比构建字符串和设置innerHTML更好的方法来填充HTML小部件?

  •  2
  • MandoMando  · 技术社区  · 14 年前

    使用xmlxslt,可以用HTML构建一个好的模板,将其转换为XSLT,并使用来自服务器的XML数据动态填充客户端的小部件。

    JSON和JSONP非常适合与服务器端交互和在JS中操作数据。在呈现JSON数据时,我看到的大多数示例都使用JS连接一个难看的字符串,并设置某个元素的innerHTML来呈现它。

    有没有一种简单的浏览器兼容的方法来创建html小部件并用JSON填充它们,而不涉及到字符串敲打或构建DOM元素的负载?

    3 回复  |  直到 14 年前
        1
  •  1
  •   Community pid    7 年前

    正如其他答案中提到的,您需要的是一种基于javascript的模板语言。这里面有一个很好的列表 related question . 只是为了突出几个, mustache 是干净的,简单的和移植到许多语言。我相信Twitter正在使用它。 Google Closure template language 它可以在JavaScript和Java中工作。显然,谷歌已经对这一点进行了实战测试。

    其他主要的JS库都有模板作为插件或库的一部分。我知道jQuery至少有一个插件,并计划在v1.5的路线图上提供一个。Dojo有一个 clone of Django's templating language

    还有其他的,但我认为那将是最棒的。

        2
  •  1
  •   donohoe    14 年前

    你应该看到John Resiq的这篇博文: JavaScript Micro-Templating

    它有一个简单的微模板代码,你可以重复使用。它是这样的:

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

    因此,模板将位于标记中:

    <script type="text/html" id="item_tmpl">
      <div id="<%=id%>" class="<%=(i % 2 == 1 ? " even" : "")%>">
        <div class="grid_1 alpha right">
          <img class="righted" src="<%=profile_image_url%>"/>
        </div>
        <div class="grid_6 omega contents">
          <p><b><a href="/<%=from_user%>"><%=from_user%></a>:</b> <%=text%></p>
        </div>
      </div>
    </script>
    

    要使用它:

    var results = document.getElementById("results");
    results.innerHTML = tmpl("item_tmpl", dataObject);
    

    不是我的密码 . 点击链接获取更多信息。

        3
  •  0
  •   davehauser    14 年前

    jQuery 还有一些模板的jQuery插件。例如 http://ivorycity.com/blog/jquery-template-plugin/