开发者

print object.object with mustache

Is there a way to do something like this:

var html,
    templ = '<p>{{config.title}}</p>',
    data = {config: {title: 'some text'}};
html = Mustache.to_html(templ, data);
alert(html);
开发者_如何学编程

With the Mustache library? Or maybe with some other library.


Use moustache contexts:

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

-> '<p>some text</p>'


https://github.com/janl/mustache.js Usage

A quick example how to use mustache.js:

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

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

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

template is a simple string with mustache tags and view is a JavaScript object containing the data and any code to render the template.


Insted of mustache use underscore.js:

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

Be careful: the data You put in Your template is unescaped.

There is one more think:
If Your templateStructure contains 'null' You will get an error. To make it work do this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜