打印带有胡子的object.object

时间:2011-03-28 12:58:03

标签: javascript mustache

有没有办法做这样的事情:

var html,
    templ = '<p>{{config.title}}</p>',
    data = {config: {title: 'some text'}};
html = Mustache.to_html(templ, data);
alert(html);

使用Mustache library? 或者也许还有其他一些图书馆。

3 个答案:

答案 0 :(得分:1)

使用胡须上下文:

var html,
    templ = '<p>{{#config}}{{title}}{{/config}}</p>',
    data = {config: {title: 'some text'}};
html = Mustache.to_html(templ, data);
alert(html);

- &GT; '<p>some text</p>'

答案 1 :(得分:0)

https://github.com/janl/mustache.js 使用

如何使用mustache.js的简短示例:

var view = {
  title: "Joe",
  calc: function() {
    return 2 + 4;
  }
}

var template = "{{title}} spends {{calc}}";

var html = Mustache.to_html(template, view);

template是一个带有mustache标签的简单字符串,view是一个JavaScript对象,包含数据和用于呈现模板的任何代码。

答案 2 :(得分:0)

小胡子的使用使用underscore.js:

_.templateSettings = { interpolate : /\{\{(.+?)\}\}/g };
var templateStructure = 'Hello {{ name }}!';
var template = _.template(templateStructure);
alert(template(yourObject));

小心:您放入模板的数据未转义。

还有一个想法:
如果您的templateStructure包含'null',您将收到错误消息。 为了使其工作,请执行以下操作:

var templateStructure = 'Hello {{ name }}! Did You know that "null" will provide an error?';
    templateStructure.replace(/null/g, 'NULL_REPLACEMENT');
var template = _.template(templateStructure);
var out = template(yourObject);
    out = template.replace(/NULL_REPLACEMENT/g, 'null');
alert(out);