带有数组的Mustache.js,最后一项的异常

时间:2013-10-02 21:32:42

标签: javascript mustache

var template = "multi: {{#answerVOs}}{{answer}}; {{/answerVOs}}";

// need => multi:option1;选项2; option3(最后没有分号和空格)

var json = {
"answerVOs": [ 
  { "answer" : "option 1"
  },
  { "answer" : "option 2"
  },
  { "answer" : "option 3"
  }
]
};

document.getElementById("answers").innerHTML = Mustache.to_html(template, json);

http://jsfiddle.net/casadev/GEbe8/1/

我需要显示数组中的最后一项而不使用分号和空格,任何想法。

编辑:PHP代码

class ChoiceVO extends \ValueObject {

public $id;
public $question;
public $answer;
public $answerformat;
public $fraction;
public $feedback;
public $feedbackformat;

public $replace = "function () { var result = ''; for( var i = 0; i < this.answers.length; i++ ) { result += this.answers[i].answer + (i !== this.answers.length - 1 ? '; ' : '');}return result;}";

function __construct($args=null) {
    parent::__construct($args);
}

}

1 个答案:

答案 0 :(得分:0)

根据Github页面上的Mustache.js文档,可以将函数传递给数据并使用模板标记调用它。所以你能做的就是这样(注意这段代码是未经测试的):

var template = 'multi: {{listAnswers}}';
var context = {
    answers: [
        { answer: 'Answer 1' },
        { answer: 'Answer 2' },
        { answer: 'Answer 3' }
    ],
    listAnswers: function () {
        var result = '';
        for( var i = 0; i < this.answers.length; i++ ) {
            result += this.answers[i].answer + (i !== this.answers.length - 1 ? '; ' : '');
        }
        return result;
    }
};

document.getElementById('answers').innerHTML = Mustache.render(template, context);

经过一些反馈

要在解析JSON之后添加函数,请执行以下操作:

var json = '{"answers":[{"answer":"Answer 1"},{"answer":"Answer 2"},{"answer":"Answer 3"}]}'; // Server response
var context = JSON.parse(json); // JSON parsed to JavaScript Object

// Add method in JavaScript, NOT PHP.
context.listAnswers = function () {
    var result = '';
    for( var i = 0; i < this.answers.length; i++ ) {
        result += this.answers[i].answer + (i !== this.answers.length - 1 ? '; ' : '');
    }
    return result;
};

document.getElementById('answers').innerHTML = Mustache.render(template, context);