Handlebar helper syntax in Ember CLI

帅比萌擦擦* 提交于 2019-12-10 21:28:15

问题


In this post

Iterating over basic “for” loop using Handlebars.js

An example of a 'repeat' helper is layed out.


helper

Handlebars.registerHelper('times', function(n, block) {
    var accum = '';
    for(var i = 0; i < n; ++i)
        accum += block.fn(i);
    return accum;
});


template

{{#times 10}}
    <span>{{this}}</span>
{{/times}}

I can't seem to write this out the 'CLI' way... can someone enlighten me?

First of all, it will be it's own helper file in /helpers , and it should have a dash so the resolver recognizes it. - so I wouldn't be registering it explicitly.


Default generated helper looks like this helpers/repeat-times.js (template should be the same...)

import Ember from 'ember';

export function repeatTimes(input) {
  return input;
}

export default Ember.Handlebars.makeBoundHelper(repeatTimes);


so, no need to register, no need to set the name... I just can't find clear docs on the syntax. :/ (I took 20 or so stabs at it...)

Or should I be making a component instead? as suggested here: Block helper with ember-cli


回答1:


@Kalman is right that you can't register a bound helper with block notation, so in this case I would recommend a component, which was referenced in the comment.

However, for those that might have found this question and still want to create a handlebars helper in ember-cli, you'll want to use the makeBoundHelper function.

For example, here's a current-date helper that I use:

// app/helpers/current-date.js
import Ember from 'ember';

export default Ember.Handlebars.makeBoundHelper(function() {
  return moment().format('LL'); // Using moments format 'LL'
});

Then, in your handlebars template, you can use this:

{{current-date}}

Which yields a date like March 5, 2015



来源:https://stackoverflow.com/questions/28865379/handlebar-helper-syntax-in-ember-cli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!