[英]handlebars.js template with custom helper to slice data array
im trying to set up a handlebars template using a custom helper but i can't seem to get it to work. 我试图使用自定义帮助程序来设置车把模板,但我似乎无法使其正常工作。 The block helper should be able to slice my data array like it says here .
块助手应该能够切开我的数据阵列像它说在这里 。
When i call every index in my array without using the helper my template it works properly. 当我在不使用帮助程序的情况下调用数组中的每个索引时,模板就会正常工作。
This is my template 这是我的模板
<script id="template_marcas" type="text/x-handlebars-template">
{{#datos_marcas}}
<div class="large-3 small-3 columns marca_item">
<div class="marca_content">
<h3>{{img}}</h3>
<p>{{descp}}</p>
<a href="{{href}}">Ver descuentos</a>
</div>
</div>
{{/datos_marcas}}
</script>
My data array: 我的数据数组:
var data_marcas = {
datos_marcas: [
{
"img":"alverto",
"descp":"Descripción Marta",
"href":"test"
},
{
"img":"marta",
"descp":"Descripción Marca",
"href":"test"
},
{
"img":"marca",
"descp":"Descripción Marca",
"href":"test"
} //etc.....
]
};
And this is the helper i'm trying to use 这是我要使用的助手
Handlebars.registerHelper('slice', function(context, block) {
var ret = "",
offset = parseInt(block.hash.offset) || 0,
limit = parseInt(block.hash.limit) || 5,
i = (offset < context.length) ? offset : 0,
j = ((limit + offset) < context.length) ? (limit + offset) : context.length;
for(i,j; i<j; i++) {
ret += block(context[i]);
}
return ret;
});
EDIT 编辑
I'm trying to use the helper as below, perhaps there is something wrong with the way i'm calling it. 我正在尝试使用以下帮助程序,也许我调用它的方式有问题。
<script id="template_marcas" type="text/x-handlebars-template">
{{#slice datos_marcas offset="1" limit="5"}}
<div class="large-3 small-3 columns marca_item">
<div class="marca_content">
<h3>{{img}}</h3>
<p>{{descp}}</p>
<a href="{{href}}">Ver descuentos</a>
</div>
</div>
{{/slice}}
</script>
I upgraded this so you can use negative offset to strip from the end of the array as per ECMA Array.slice. 我对此进行了升级,因此您可以按照ECMA Array.slice使用负偏移量从数组末尾剥离。
Handlebars.registerHelper('slice', function (context, options) {
var ret = "",
offset = parseInt(options.hash.offset, 10) || 0,
limit = parseInt(options.hash.limit, 10) || 5,
i,
j;
if (offset < 0) {
i = (-offset < context.length) ? context.length - (-offset) : 0;
} else {
i = (offset < context.length) ? offset : 0;
}
j = ((limit + i) < context.length) ? (limit + i) : context.length;
for (i, j; i < j; i++) {
ret += options.fn(context[i]);
}
return ret;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.