LoginSignup
14
6

More than 5 years have passed since last update.

Handlebarsことはじめ

Last updated at Posted at 2015-05-27
npm install handlebars

handlebars

handlebars: command not found

パスが通っていないので
./node_modules/.bin/handlebars

文法は公式を参照
Handlebars.js: Minimal Templating on Steroids

いい感じに名前空間くぎってのコンパイルの仕方はnpmリポジトリ参考
npm : gulp-handlebars

ことはじめるまでもありませんでした。

・・・なんですが、一つだけ。
今回初めてjavascriptテンプレートというものを使ったのであんまり空気感がわかってませんでしたが、handlebarsはifの制御構文は記述できるものの、評価に式を使う事はできないというのはちょっと戸惑います。

OK
{{#if something }}
<p>hogehoge</p>
{{/if}}

NG
{{#if (num > 10) }}
<p>hogehoge</p>
{{/if}}

公式によると false,undefined,null,0,"",[]以外はture扱いという事らしいです。
テンプレートに流す前に評価してやらないといけないと言う事ですね。まぁつまりロジックはロジック側でということらしいです。

ちなみに、handlebarsではこのifなどの制御構文はHelper関数で定義していて、さらに自作のHelper関数を追加できます。ということは式を評価するifっぽいのつくれるのでは?

Handlebars.registerHelper('myif', function(val1,operator,val2, opt) {
  var cond;

  if ( operator === '===' )
  {
    cond = val1 === val2;
  }
  else if ( operator === '!==' )
  {
    cond = val1 !== val2;
  }
  else if ( operator === '==' )
  {
    cond = val1 == val2;
  }
  else if ( operator === '!=' )
  {
    cond = val1 != val2;
  }
  else if ( operator === '>' )
  {
    cond = val1 > val2;
  }
  else if ( operator === '>=' )
  {
    cond = val1 >= val2;
  }
  else if ( operator === '<' )
  {
    cond = val1 < val2;
  }
  else if ( operator === '<=' )
  {
    cond = val1 <= val2;
  }

  if (cond) {
    return opt.fn(this);
  } else {
    return opt.inverse(this);
  }
});
sample.hbs
{{#myif num1 ">=" num2}}
<p>TRUE!</p>
{{else}}
<p>FALSE!!</p>
{{/myif}}
index.html
// sample.hbsをコンパイルした後
var html1 = Handlebars.templates['sample.hbs']({
  num1 : 10,
  num2 : 20,
});

console.log(html); // <p>FALSE!!</p>

とまぁ簡単にできますが、こういうことをしてテンプレートにロジックを持って行くのが良くないという思想だと思いますので良くない気がします。以上。

special thanks

14
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
6