EmberJS / HandlebarsJS的自定义for-loop帮助器 [英] Custom for-loop helper for EmberJS/HandlebarsJS
问题描述
两小时前一小时,我开始:嵌套HandlebarsJS#每个助手EmberJS不工作
A small two hours ago I started: Nested HandlebarsJS #each helpers with EmberJS not working
我自己想到一个可接受的临时解决方案后不久,问题仍然没有得到解决。我的问题并不止于此。
Shortly after I figured an acceptable temporary solution myself, question is still unaswered. My problems didn't stop there though.
我现在正在尝试创建一个自定义帮助器,它将循环遍历一个对象数组,但不包括第一个索引 - 相当多的 i = 1; i< length; i ++){}
。我已经在网站上阅读过您需要获取上下文长度并将其传递给选项 - 考虑到您的函数如下所示: forLoop(context,options)
。
I am now trying to make a custom helper which will loop through an array of objects, but exclude the first index - pretty much: for(i = 1; i < length; i++) {}
. I've read on websites you have to get the length of your context and pass it to options - considering your function looks like: forLoop(context, options)
.
然而,上下文是一个字符串而不是一个实际的对象。当您执行 .length
时,您将获得字符串的长度,而不是数组的大小。当我将它传递给选项时,没有任何反应 - 不要太提及浏览器冻结。
However, context is a string rather than an actual object. When you do a .length
, you will get the length of the string, rather than the size of the array. When I pass that to options, nothing happens - not too mention browser freezes.
然后我首先尝试一个 getPath
在将其传递给选项之前,这将返回一个空字符串。
I then first tried to do a getPath
before passing it to options, this returns an empty string.
我应该做什么,而之前我做了for循环代码,只是HandlebarsJS,工作,但是EmberJS似乎没有这样做,为什么?
What am I supposed to do instead, I made the for-loop code before for just HandlebarsJS and that worked, but EmberJS doesn't seem to take it, why?
编辑:我也很遵循: http://handlebarsjs.com/block_helpers.html - >简单迭代器
I pretty much also followed: http://handlebarsjs.com/block_helpers.html -> Simple Iterators
推荐答案
在尝试了很长时间后,我自己解决了这个问题。
I solved this myself after trying for a long time.
HandlebarsJS方法(如网站上所述)不再适用于EmberJS,现在如下:
The HandlebarsJS method (as described on the site) is no longer valid for EmberJS, it's now as follows:
function forLoop(context, options) {
var object = Ember.getPath(options.contexts[0], context);
var startIndex = options.hash.start || 0;
for(i = startIndex; i < object.length; i++) {
options(object[i]);
}
}
哎,你甚至可以将for循环扩展到包含一个索引值!
Heck, you could even extend the for-loop to include an index-value!
function forLoop(context, options) {
var object = Ember.getPath(options.contexts[0], context);
var startIndex = options.hash.start || 0;
for(i = startIndex; i < object.length; i++) {
object[i].index = i;
options(object[i]);
}
}
这是一个可变起始索引的工作for循环。您可以在模板中使用它:
This is a working for-loop with variable start index. You use it in your templates like so:
{{#for anArray start=1}}
<p>Item #{{unbound index}}</p>
{{/for}}
这篇关于EmberJS / HandlebarsJS的自定义for-loop帮助器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!