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

//需要=>多:选项1;选项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);
}

}
4

1 回答 1

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);
于 2013-10-02T22:44:20.727 回答