简体   繁体   中英

Ending a smarty foreach loop with 'and'

I'm pulling a list of names and dates out of an array that I would like to render as a natural language sentence, with the penultimate item followed by 'and', then the last item.

Here's my code:

<p>In the past, we&rsquo;ve interviewed the likes of {foreach from=$interviewees key=k item=v name=people}
<a href="https://www.example.com/interviews/{$v}.html">{$k}</a
{if $smarty.foreach.people.last}. {else},{/if} {foreachelse}{/foreach}

where key is the person's name, item is the url in the form of a date (201509). This outputs a nice comma separated list, but how do I insert a natural looking and to finish the list?

I'm hoping for the following output:

<p>In the past, we&rsquo;ve interviewed the likes of 
<a href="https://www.example.com/interviews/201405.html">Forename Surname</a>,  
<a href="https://www.example.com/interviews/201408.html">Forename Surname</a>,  
<a href="https://www.example.com/interviews/201403.html">Forename Surname</a> 
and  <a href="https://www.example.com/interviews/201312.html">Forename Surname</a>.

Thanks for any help!

Try this:

<p>In the past, we&rsquo;ve interviewed the likes of {foreach     
from=$interviewees key=k item=v name=people}
{if $smarty.foreach.people.last} and {/if}
<a href="https://www.example.com/interviews/{$v}.html">{$k}</a>
{if $smarty.foreach.people.last}.{else}
   {if $smarty.foreach.people.iteration+1!=$smarty.foreach.people.total},{/if}  
{/if} {foreachelse}{/foreach}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM