핸들 바의 항목을 반복 할 때 {{@index}}에 오프셋 추가
내장 도우미를 사용하여 Handlebars 의 목록을 반복하고 each
있습니다. 각 블록 내에서 항목의 연속 번호를 인쇄하기 위해 현재 루프 인덱스 {{@index}}
를 참조하고 있습니다 .
<script id="list-item-template" type="text/x-handlebars-template">
{{#each items}}
<li class="topcoat-list__item">
<a href="#{{@index}}">Item number {{@index}}</a>
</li>
{{/each}}
</script>
그러면 다음과 같은 출력이 제공됩니다.
- 항목 번호 0
- 항목 번호 1
- 항목 번호 2
- ....
문제는 0 대신 1로 시작하는 오프셋 된 인덱스를 표시하고 싶다는 것입니다.
나는 같은 인덱스에 대한 계산을 수행하려고 시도 {{@index+1}}
했지만 이것은 단지
포착되지 않은 오류 : 구문 분석 오류
핸들 바는 이러한 상황을 처리하는 사용자 지정 도우미를 작성할 수있는 가능성을 제공합니다. 예를 들어 더하기 및 빼기와 같은 식에 대한 계산을 수행 할 수있는 도우미 함수입니다.
아래 함수는 단순히 값을 1 씩 증가시키는 새 도우미를 등록합니다.
var Handlebars = require('handlebars');
Handlebars.registerHelper("inc", function(value, options)
{
return parseInt(value) + 1;
});
그런 다음 다음 inc
과 같은 키워드를 사용하여 핸들 바 표현식 내에서 사용할 수 있습니다 .
{{inc @index}}
실제 답변 : https://stackoverflow.com/a/46317662/1549191
수학 핸들 바를 등록하고 모든 수학 연산을 수행합니다.
app.engine('handlebars', exphbs({
helpers:{
// Function to do basic mathematical operation in handlebar
math: function(lvalue, operator, rvalue) {lvalue = parseFloat(lvalue);
rvalue = parseFloat(rvalue);
return {
"+": lvalue + rvalue,
"-": lvalue - rvalue,
"*": lvalue * rvalue,
"/": lvalue / rvalue,
"%": lvalue % rvalue
}[operator];
}
}}));
app.set('view engine', 'handlebars');
그런 다음보기에서 직접 작업을 수행 할 수 있습니다.
{{#each myArray}}
<span>{{math @index "+" 1}}</span>
{{/each}}
나는 당신이 사용할 수 있다고 믿습니다 ...
{{math @index "+" 1}}
Mobiletainment의 답변을 확장하기 위해이 솔루션은 값이 증가하여 인수로 전달되도록합니다. 값이 전달되지 않으면 기본값 1이 사용됩니다.
Handlebars.registerHelper('inc', function(number, options) {
if(typeof(number) === 'undefined' || number === null)
return null;
// Increment by inc parameter if it exists or just by one
return number + (options.hash.inc || 1);
});
그런 다음 템플릿 내에서 다음을 작성할 수 있습니다.
{{inc @index inc=2}}
핸들 바 코드 하단에 짧은 스크립트 태그를 추가하여이 문제를 직접 해결했습니다!
@index를 호출 할 때마다 클래스를 추가하면 아래 jQuery 코드가 작동합니다 (바닐라 JS를 사용하여 수행 할 수도 있음).
<p class="create_index">
{{@index}}
</p>
<script>
$(".create_index").text(parseInt($(".create_index").text())+1)
</script>
edit 4/28- This has changed to use vanilla JS for better backwards compatibility (i.e. IE7, 8):
<span class="create_index"></span>
<script>
var divs = document.querySelectorAll('.create_index');
for (var i = 0; i < divs.length; ++i) {
divs[i].innerHTML = i + 1;
}
</script>
document.querySelectorAll
has great compatibility but could also be document.getElementsByClassName("create_index")
The handlebars-helpers library has a fairly thorough mathematics library in lib/math.js
, including a general purpose {{add a b}}
helper defined as follows:
/**
* Return the product of a plus b.
*
* @param {Number} a
* @param {Number} b
* @api public
*/
helpers.add = function(a, b) {
return a + b;
};
If you don't want to copy and paste this into your project and you have the possibility to use npm
, you can get this dependency as follows:
npm install handlebars-helpers --save
Then, you can register the math helpers as follows:
const handlebars = require('handlebars'),
handlebarsHelpers = require('handlebars-helpers');
handlebarsHelpers.math({
handlebars: handlebars
});
Throwing my solution in here. CSS counters.
body {
counter-reset: section; /* Set a counter named 'section', and its initial value is 0. */
}
h3::before {
counter-increment: section; /* Increment the value of section counter by 1 */
content: counter(section); /* Display the value of section counter */
}
I was stuck on this and it was a nicer solution compared to adding a new helper.
I was using nodejs and express-handlebars as template engine and facing same problem. And this is how I managed to solve.
You can create a folder and a js file inside it where you can create your own custom helpers that takes index and returns incrementing it by 1.
module.exports = {
formatIndex: function(index) {
return index+1;
}
}
Remember to register helper in your application(in my case app.js). I have used express-handlebars so I have reistered helper in this way:
app.engine('handlebars', exphbs({defaultLayout: 'home', helpers: { formatIndex }}));
Note: You have to import formatIndex before registering.
Then you can use it in your view as:
{{#each assignments}}
<div>{{formatIndex @index }}</div>
{{/if}}
ReferenceURL : https://stackoverflow.com/questions/22103989/adding-offset-to-index-when-looping-through-items-in-handlebars
'program story' 카테고리의 다른 글
자바 스크립트에서 C # (컨트롤러)로 datetime 전달 (0) | 2020.12.24 |
---|---|
Facebook Graph API는 이메일 주소를 반환하지 않습니다. (0) | 2020.12.24 |
MySQL Alter 테이블로 인해 오류 : 잘못된 NULL 값 사용 (0) | 2020.12.24 |
RecyclerView에서 불일치가 감지되었습니다. 스크롤하는 동안 RecyclerView의 내용을 변경하는 방법 (0) | 2020.12.24 |
"서명 된"키워드의 실제 사용은 무엇입니까? (0) | 2020.12.24 |