Is there something like n:repeat?

bernhard
Member | 51
+
0
-

First of all let me thank you for this brilliant template engine!!!

I'd like to multiply an image tag several times to make a star rating:

<img class='star' src="star.svg" n:repeat="$stars">
<img class='star' src="star-o.svg" n:repeat="5-$stars">

What would be the best way to do this? This is what I came up with:

{for $i=0;$i < $item->stars(); $i++}
<img class='star' src="star.svg">
{/for}
{for $i=0;$i < $item->stars(true); $i++}
<img class='star' src="star-o.svg">
{/for}

Am I missing anything or would this be a candidate for a feature request? Thx.

PS: First i tried n:foreach=“$stars” but (obviously) that did not work. Also n:foreach=“$stars as $i” failed.

Last edited by bernhard (2022-05-04 17:58)

Pepino
Member | 256
+
-1
-

https://latte.nette.org/en/filters#…

Last edited by Pepino (2022-05-04 18:48)

bernhard
Member | 51
+
0
-

Thx, I've found that during my research but how would I use that for my image tag?

Pepino
Member | 256
+
-3
-
{="<img src…>"|noescape|repeat:$stars}

Last edited by Pepino (2022-05-05 09:02)

bernhard
Member | 51
+
0
-

Thx!

dkorpar
Member | 135
+
+1
-

Having HTML in literal string is never a good idea…
I'd rather use something like n:foreach=“range(1, 5) as $rating” here

so something like this works:

<img class='star' src="star.svg" n:foreach="range(1, 5) as $rating">

you can even use $rating inside tag like


<img class='star' src="star-{$rating}.svg" n:foreach="range(1, 5) as $rating">

Last edited by dkorpar (2022-05-09 09:40)

David Grudl
Nette Core | 8218
+
0
-

@dkorpar you mean n:foreach

dkorpar
Member | 135
+
0
-

David Grudl wrote:

@dkorpar you mean n:foreach

Yes, edited, thanks :)

bernhard
Member | 51
+
0
-

@dkorpar good idea, but it does not work for my use case… I need star.svg for a filled star and star-o for a non-filled star.

<img class='star' src='/site/templates/img/star.svg' n:foreach="range(1,$stars) as $s">
<img class='star' src='/site/templates/img/star-o.svg' n:foreach="range($stars,5) as $s">

The problem here is, that if one review has 5 stars it will nonetheless print a non-filled star at the end as it states n:foreach="range(5,5)… which will echo the tag once.

This is my current solution:

{for $i=1;$i<=5;$i++}
  {var $star = $i<=$item->stars() ? 'star.svg' : 'star-o.svg'}
  <img class='star' src='/site/templates/img/{$star}'>
{/for}

I'd still prefer this, but it seems like a very little thing to not have.

<img class='star' src='/site/templates/img/star.svg' n:repeat="$stars">
<img class='star' src='/site/templates/img/star-o.svg' n:repeat="5-$stars">

Last edited by bernhard (2022-05-09 11:42)

stepos2
Member | 53
+
+1
-
<img class="star" src="/site/templates/img/star{$s > $stars ? '-o'}.svg" n:foreach="range(1, 5) as $s">
bernhard
Member | 51
+
0
-

Nice 😎 Thx!

Last edited by bernhard (2022-05-09 13:02)