Hello everyone,
I would like to know if there is a syntax to write a for loop from 1 to n.
Thanks in advance !
Hello everyone,
I would like to know if there is a syntax to write a for loop from 1 to n.
Thanks in advance !
Your can create the list in extension:
{m:for variable | Sequence{1, 2, 3, 4}}
{m:variable}
{m:endfor}
Thanks for your answer.
I thought about that but I’m looking for a solution without knowing the last number. For example, I would like a for loop between 1 and ‘sys->size()’.
OK you want to keep track of the current iteration number. To do that you can create a Java class that will keep the current value and that you can reset and increment. Then in your template you can do something like this:
'variable'.resetCounter()
{m:for variable | sys}
'variable'.incrementCounter()
{m:variable}
'variable'.getCounter()
{m:endfor}
A simple Java class:
public class CounterServices {
private static final int COUNTER_START = 0;
private final Map<String, Integer> counters = new HashedMap<>();
public void resetCounter(String name) {
counters.put(name, COUNTER_START);
}
public void incrementCounter(String name) {
counters.put(name, counters.getOrDefault(name, COUNTER_START) + 1);
}
public int getCounter(String name) {
return counters.getOrDefault(name, COUNTER_START);
}
}
It would be nice to have this out of the box. I opened the following issue:
Thanks a lot ! I will do it like that.