program story

핸들 바의 항목을 반복 할 때 {{@index}}에 오프셋 추가

inputbox 2020. 12. 24. 23:41
반응형

핸들 바의 항목을 반복 할 때 {{@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

반응형