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

发布于 2024-09-14 18:35:20 字数 262 浏览 7 评论 0原文

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

JSON 和 JSONP 非常适合与服务器端交互以及在 JS 中操作数据。当谈到渲染 JSON 数据时,我见过的大多数示例都使用 JS 连接一个丑陋的字符串并设置某些元素的 innerHTML 来渲染它。

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

With XML XSLT, it is possible to build a nice template in HTML, convert it to XSLT and use xml data coming from the server to dynamically populate widgets on the client side.

JSON and JSONP are great for interacting with the server side and manipulating the data in JS. When it comes to rendering the JSON data, most examples I've seen use JS to concatenate an ugly string and set the innerHTML of some element to render it.

Is there an easy browser compatible way of creating html widgets and populating them with JSON that doesn't involve string banging or building loads of DOM elements?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情话已封尘 2024-09-21 18:35:20

正如其他答案中提到的,您正在寻找的是一种基于 javascript 的模板语言。这个相关问题中有一个非常好的列表。需要强调的是,mustache 干净、简单,并且可以移植到多种语言。我相信 Twitter 正在使用它。 Google Closure 具有 模板语言,适用于 JavaScript 和 Java。显然,这已经经过谷歌的实战测试。

其他主要 JS 库都将模板作为插件或库的一部分。我知道 jQuery 至少有一个插件,并且正在为 v1.5 的路线图上规划一个插件。 Dojo 有一个Django 模板语言的克隆,看起来很漂亮好的。

还有其他的,但我认为这将是百里挑一。

我实际上并没有使用其中任何一个,因为我使用的是自制的,但我可以告诉你,它们非常好用,我强烈推荐它们而不是字符串连接或在服务器上做更多工作。

As mentioned in other answers, what you're looking for is a javascript based templating language. There is a pretty good list going in this related question. Just to highlight a couple, mustache is clean, simple and ported to many many languages. I believe its being used by Twitter. Google Closure has template language that works in both JavaScript and Java. That's been battle tested by Google obviously.

Other major JS libraries each have templating as plugins or part of the library. I know jQuery has at least one plugin and is planning one on the roadmap for v1.5. Dojo has a clone of Django's templating language that looks pretty nice.

There are others, but I think that's going to be the cream of the crop.

I don't actually use any of these, because I use a home grown one, but I can tell you that they are very nice to work with and I highly recommend them over string concatenation or doing more work on the server.

濫情▎り 2024-09-21 18:35:20

您应该看到 John Resiq 的这篇博文:JavaScript 微模板

您可以重复使用的简单微模板代码。它是这样的:

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

需要明确的是 - 上面的示例取自博客文章,并且不是我的代码。请点击链接了解更多信息。

You should see this blog post by John Resiq: JavaScript Micro-Templating

It has a simple micro-templating code you can re-use. It goes like this:

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

So you template would be in the markup:

<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>

To use it:

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

To be clear - the above example was taken from the blog post and is not my code. Follow the link for more info.

寂寞美少年 2024-09-21 18:35:20

您可以使用 jQuery 和某种 jQuery 模板插件。例如 http://ivorycity.com/blog/jquery-template-plugin/(看看这个页面,有一些不错的示例)

You could use jQuery and some sort of jQuery Plugin for Templates. For example http://ivorycity.com/blog/jquery-template-plugin/ (have a look at this page, there are some nice samples)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文