I want to have a counter variable of type integer while rendering my html using thymeleaf but the counter variable is incremented unexpectedly. Below is my code. Please help.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en"
xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:with="mycounter = 0">
<div th:with="mycounter=${mycounter + 1}">
<span th:text="${mycounter}"></span> <!-- result: 1 -->
</div>
<div th:with="mycounter=${mycounter + 1}">
<span th:text="${mycounter}"></span> <!-- result: 1 , expected: 2-->
</div>
</div>
</body>
</html>
You can achiveve it using following approach:
On server-side implement a simple class called Counter:
public class Counter
{
private int count;
public Counter()
{
count = 0;
}
public Counter(int init)
{
count = init;
}
public int get()
{
return count;
}
public void clear()
{
count = 0;
}
public int incrementAndGet()
{
return ++count;
}
public String toString()
{
return ""+count;
}
}
In your servlet code add:
context.addAttribute("counter", new Counter());
In your template you can use and increment it like this:
<div th:with="mycounter = ${counter.get()}">
<div th:with="mycounter=${counter.incrementAndGet()}">
<span th:text="${mycounter}"></span> <!-- result: 1 -->
</div>
<div th:with="mycounter=${counter.incrementAndGet()}">
<span th:text="${mycounter}"></span> <!-- result: 2 , expected: 2-->
</div>
</div>