feat(for tag): Provide the counter 0 indexed to the context
Closes #121
This commit is contained in:
@@ -2,6 +2,11 @@
|
||||
|
||||
## Master
|
||||
|
||||
### Enhancements
|
||||
|
||||
- Adds `counter0` to for loop context allowing you to get the current index of
|
||||
the for loop 0 indexed.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- Fixes a potential crash when using the `{% for %}` template tag with the
|
||||
|
||||
@@ -114,6 +114,7 @@ class ForNode : NodeType {
|
||||
"first": index == 0,
|
||||
"last": index == (count - 1),
|
||||
"counter": index + 1,
|
||||
"counter0": index,
|
||||
]
|
||||
|
||||
return try context.push(dictionary: ["forloop": forContext]) {
|
||||
|
||||
@@ -83,6 +83,12 @@ func testForNode() {
|
||||
try expect(try node.render(context)) == "112233"
|
||||
}
|
||||
|
||||
$0.it("renders the given nodes while providing item counter") {
|
||||
let nodes: [NodeType] = [VariableNode(variable: "item"), VariableNode(variable: "forloop.counter0")]
|
||||
let node = ForNode(resolvable: Variable("items"), loopVariables: ["item"], nodes: nodes, emptyNodes: [])
|
||||
try expect(try node.render(context)) == "102132"
|
||||
}
|
||||
|
||||
$0.it("renders the given nodes while filtering items using where expression") {
|
||||
let nodes: [NodeType] = [VariableNode(variable: "item"), VariableNode(variable: "forloop.counter")]
|
||||
let `where` = try parseExpression(components: ["item", ">", "1"], tokenParser: TokenParser(tokens: [], environment: Environment()))
|
||||
|
||||
@@ -57,23 +57,24 @@ The for block sets a few variables available within the loop:
|
||||
|
||||
- ``first`` - True if this is the first time through the loop
|
||||
- ``last`` - True if this is the last time through the loop
|
||||
- ``counter`` - The current iteration of the loop
|
||||
- ``counter`` - The current iteration of the loop (1 indexed)
|
||||
- ``counter0`` - The current iteration of the loop (0 indexed)
|
||||
|
||||
For example:
|
||||
|
||||
.. code-block:: html+django
|
||||
|
||||
{% for user in users %}
|
||||
{% if forloop.first %}
|
||||
This is the first user.
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% for user in users %}
|
||||
{% if forloop.first %}
|
||||
This is the first user.
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
|
||||
.. code-block:: html+django
|
||||
|
||||
{% for user in users %}
|
||||
This is user number {{ forloop.counter }} user.
|
||||
{% endfor %}
|
||||
{% for user in users %}
|
||||
This is user number {{ forloop.counter }} user.
|
||||
{% endfor %}
|
||||
|
||||
|
||||
``if``
|
||||
|
||||
Reference in New Issue
Block a user