Is there something like n:repeat?
- bernhard
- Member | 51
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)
- dkorpar
- Member | 135
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)
- bernhard
- Member | 51
@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)