Ответ 1
Если вы хотите использовать рули, просто возьмите модуль npm:
npm install handlebars
Затем в script вы можете использовать дескрипторы для вывода вашего вывода на основе простого шаблона, который итерации по массиву foo
и создает <p>
для каждого элемента, содержащего текст свойства bar
var handlebars = require('handlebars');
// get your data into a variable
var fooJson = require('foo.json');
// set up your handlebars template
var source = '{{#each foo}}<p>{{this.bar}}</p>{{/each}}';
// compile the template
var template = handlebars.compile(source);
// call template as a function, passing in your data as the context
var outputString = template(fooJson);
- EDIT -
Если вы хотите использовать файл шаблона .hbs вместо строки source
, вы можете использовать модуль fs
для чтения файла с помощью fs.readFile
, вызвать toString()
в возвращаемом буфере и использовать его для вызовите функцию рендеринга. Попробуйте следующее:
var handlebars = require('handlebars');
var fs = require('fs');
// get your data into a variable
var fooJson = require('path/to/foo.json');
// read the file and use the callback to render
fs.readFile('path/to/source.hbs', function(err, data){
if (!err) {
// make the buffer into a string
var source = data.toString();
// call the render function
renderToString(source, fooJson);
} else {
// handle file read error
}
});
// this will be called after the file is read
function renderToString(source, data) {
var template = handlebars.compile(source);
var outputString = template(data);
return outputString;
}