Handlebars.js サンプル

    >

Handlebars = require('handlebars');

var source = `

{{test node}}

`;

Handlebars.registerHelper('test', function(data) {

  var str ;
  var array = ["layer one","layer two","layer three"] ;
  for (var i = 0; i < data.length; i++ ) {

    str += `
    <div class="${array[i%array.length]}">
      <h2>${data[i]["term"]}</h2>
      ${data[i]["meaning"]}
    </div>
    `;

  };

  return new Handlebars.SafeString (str);
});

var template = Handlebars.compile(source);

var data = {

  node: [

{ term: "evasiveness", meaning: "ごまかし" } ,
{ term: "no way ", meaning: "とんでもない!" } ,
{ term: "at least", meaning: "少なくとも" } ,
{ term: "fuss", meaning: "散らかった" } ,
{ term: "nuisance", meaning: "迷惑" } ,
{ term: "no longer ", meaning: "もはや" } ,
{ term: "calm down", meaning: "落ち着く" } ,
{ term: "stuffy", meaning: "ぬるい" } ,
{ term: "circumstances", meaning: "状況" } ,
{ term: "duties", meaning: "職務" } ,
{ term: "certain", meaning: "確信して" } ,
{ term: "good grief.", meaning: "なんて悲しいんだ。" } ,
{ term: "a whole lot", meaning: "たくさん" } ,
{ term: "twisted ", meaning: "ねじれた" } ,
{ term: "slut", meaning: "ビッチ女" } ,
{ term: "no surprise", meaning: "驚かない" } ,
{ term: "It has to be", meaning: "それはそうなるべき" } ,
{ term: "head back", meaning: "引き返す" } ,
{ term: "in just a bit", meaning: "ほんの少し" } ,
{ term: "clingy", meaning: "ぎこちない" } ,
{ term: "ever since ", meaning: "それ以来" } ,
{ term: "cling", meaning: "しがみつく" } ,
{ term: "reckless", meaning: "無謀" } ,
{ term: "urged", meaning: "促された" } ,
{ term: "intruding", meaning: "侵入する" } ,
{ term: "drooling", meaning: "落ちる" } ,
{ term: "insult", meaning: "侮辱" } ,
{ term: "cruel", meaning: "残酷な" } ,
{ term: "disturb", meaning: "妨害する" } ,
{ term: "I'm certain", meaning: "確信しています" } ,

  ] ,

};

var result = template(data);

console.log(result) ;

const fs = require('fs');
fs.writeFile("./tmp.txt", result , function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("OK: Text was saved to ./tmp.txt.");
}); 

other

  • atom::regex
(.*)\t(.*)$
{ term: "$1", meaning: "$2" } ,

参考文献

Write Templates Like A Node.js Pro: Handlebars Tutorial

meteor – handlebars.js “each” loop inside another “each” loop 3 – Stack Overflow

this article says about the “path”.

A Beginner’s Guide to Handlebars — SitePoint

about Javascript grammers

JavaScriptにおける連想配列のforループ操作 – Qiita

note

Handlebars.registerPartial(
  'partialTemplate',
  '{{language}} is {{adjective}}. You are reading this article on {{website}}.'
);

var context={
  "language" : "Handlebars",
  "adjective": "awesome"
}
When used with the template defined below

{{> partialTemplate website="sitepoint"}} <br>
{{> partialTemplate website="www.sitepoint.com"}}
It’ll give the following result:

Handlebars is awesome. You are reading this article on sitepoint
Handlebars is awesome. You are reading this article on www.sitepoint.com

お困りですか?この記事で紹介していることをマンツーマンで指導、解説、代行します。まずはお気軽にお問い合わせください。


関連するかもしれない記事

ごめんなさい!この記事には関連記事が1つも見つかりませんでした。

Close Menu