2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Assemble で {{#each}} 中、指定回数毎に処理をしたい

Last updated at Posted at 2015-08-20

Assemble で JSON とかを {{# each}} する時、規定数のタグ毎にタグで囲いたい時とか

15/10/22 npm module 化した npmjs/handlebars-helper-do-once-in-times

Assemble の official サイトの "Kiss my shiny metal ass!" とかのサンプル文言は好きだけど、なんとなく色々捜しにくいと思うのは私だけでしょうか。
ビルトインのヘルパーは見つける事ができなかったので、ググりまくったら stackoverflow で発見。そのままだとちょっと挙動がおかしかったので、修正したやつの備忘録。

例えば li タグ三つ毎に ul タグで囲いたいような場合

custom-helper.js
module.exports.register = function (Handlebars, options)  {
  Handlebars.registerHelper("xtimes", function(index_count, mod, block) {
    if(parseInt(index_count) % (mod) === 0 && index_count !== 0){
      return block.fn(this);
    }
  });
};
Gruntfile.js
    assemble: {
      site: {
        options: {
          helpers: [
            'custom-helper.js'
          }
        }
      }
    },
hoge.hbs
<ul class="triplet">
{{# each list }}
{{#xtimes @index 3}}</ul><ul class="triplet">{{/xtimes}}
  <li>{{name}}</li>
{{/ each}}
</ul>
result.html
<ul class="triplet">
  <li>hoge</li><li>fuga</li><li>piyo</li>
</ul>
<ul class="triplet">
  <li>とどめ</li><li>くらえ</li><li>エメラルドスプラーッシュ</li>
</ul>
<ul class="triplet">
  <li></li><li>なにをするだーッ</li>
</ul>

{{# each}} とかのデータは関係なく、単純な repeat は helper が色々落ちてます

$ npm i handlebars-helper-repeat --save
Gruntfile.js
    assemble: {
      site: {
        options: {
          helpers: [
            'handlebars-helper-repeat'
          }
        }
      }
    },

handlebars-helper-repeat@github

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?