web-dev-qa-db-ja.com

Node.jsでフレームワーク(ex = express)を使用せずにテンプレート(ハンドルバーまたはその他の代替手段)を使用するにはどうすればよいですか?

たとえば、次のJSONドキュメント「foo.json」があります。

{
    "foo": [
        {
            "bar": "Hello World!"
        },
        {
            "bar": "The End"
        }
    ]
}

Node.jsで、テンプレート(ハンドルバーなど)を使用して、JSONドキュメントから次のような文字列を生成したいと思います。

<p>Hello World!</p><p>The End</p>

...次に、その文字列値をNode.jsの変数に割り当てます。最後に、さらに多くの値を変数に連結し、最終的な変数値をhtmlドキュメントとして出力します。

Expressのようなフレームワークを使用せずにこれを行うことはできますか?

14
edt

ハンドルバーを使用する場合は、npmモジュールを入手するだけです。

npm install handlebars

次に、スクリプトで、ハンドルバーを使用して、配列fooを反復処理し、barプロパティのテキストを含む各アイテムの<p>を作成する単純なテンプレートに基づいて出力をレンダリングできます。

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

-編集-

文字列sourceの代わりに.hbsテンプレートファイルを使用する場合は、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;
}
35
jshanley