2

I am trying to build a simple loop where I execute the template N times. I wrote a function that accepts a parameter and outputs string based on it and I need to execute it a bunch of times.

Following works if I explicitly define a range:

{% for t in ["0","1","2"] %}
{{ customFunction(t) }}
{% endfor %}

However I want something like loop over some arbitrary range (or even a while loop where I execute a custom function N times):

{% for t in [0..15] %}
{{ customFunction(t) }}
{% endfor %}

I also tried defining a function that returns a range ["0","1","2"] called range() and tried using in the for-loop with no luck:

{% for t in range() %}
{{ customFunction(t) }}
{% endfor %}

So not sure if this is possible.

AlexC
  • 1,395
  • 14
  • 26
  • IMHO, from reading the scant documentation, Pebble looks like a really primitive templating system without much standard functionality. You would be better off using a more mature system like ThymeLeaf or Freemarker. – Jim Garrison Aug 07 '17 at 02:51
  • I need the ability to create my own functions, Thymeleaf was not supporting this at this time and Freemarker was very clumsy at it. Freemarker was the first one I tried. Then, I tried about 5 templating engines and none allowed easy creation of functions that are backed by java. Do you know of any? – AlexC Aug 07 '17 at 04:04

1 Answers1

4

AlexC. I also had a headache with that.

I found a solution hoping it corresponding to your issue. You were almost there!

In pebble template, to use simple loop with for statement, use code as below.

{% set n = 15 %}
{% for t in range(1, n) %}
{{ customFunction(t) }}
{% endfor %}

FYI, Below is actual applied in my code where totalPageCount is from spring model value(primitive integer).

{% for i in range(1, totalPageCount) %}
<pre>
<li><a href="">{{ i }}</a></li>
</pre>
{% endfor %}

Hopefully you would make it work!

HanByul Lee
  • 351
  • 4
  • 16
  • I switched from pebble to JSP as it was just too much work to work around not having flow control when evaluating templates. – AlexC Oct 13 '17 at 16:45
  • I completely agreed with that. Pebble view template engine isn't yet powerful template. I have little bit hard time these days since I'm forced to work with pebble and new to it in my company. Anyway what about using Thymeleaf or Freemarker? – HanByul Lee Oct 15 '17 at 01:24
  • I tried both of those but it was so much easier to use JSP since this already runs in tomcat and implement custom tags that I decided that JSP is way more powerful and flexible than most templating engines out there. – AlexC Oct 15 '17 at 01:35
  • Yeah, you're right. If there were no enforcement around me, I would use JSP rather than other templating engines too. But thymeleaf and freemarker are good enough alternatives for JSP, I think. Thank you for your replies. Good luck! – HanByul Lee Oct 16 '17 at 09:53