Avoid trailing comma when emitting lists in Mustache templates

In pure Mustache there’s no (simple) way to avoid a trailing comma on a list:

{{#items}}{{.}}, {{/items}}

Which produces something like: “First, Second, Third, “

There are various ways around this. If you’re working in HTML I think the nicest is to model your list as an actual HTML list and use CSS:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8"/>
    <title>Lists</title>
    <style>
      .list {           
        margin: 0;      
        padding: 0;
      }
      .list li {           
        display: inline;             
      }
      .list li:not(:last-child):after {
        content: ", ";               
      }
    </style>
  </head>
  <body>
    <ol class="list">
      <li>First</li>
      <li>Second</li>
      <li>Third</li>
    </ol>
  </body>
</html>

Which produces: “First, Second, Third”.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.