Space between items in hit template moustache array

I have a custom hit template which includes showing a list of categories.

<h4 class="top-level-category">
       {{display_category}}
  </h4>

The output of this is comma separated, but there is no space between items e.g. category 1,category 2

I’d like to either add a space or wrap the items in a span

I have tried along the lines of:

{{#display_category}}<span class="cat-name">{{.}}</span>{{/display_category}}

Which works for items with more than one category to display - but when there is only a single category - nothing shows.

Any ideas how I can make it work for items with multiple and just a single category?

Thanks

Guy

Your code works if display_category is always an array, but from your result I suppose that if there is only one display_category then it is directly a string and not an array.

In that case you have 2 solutions:

  • Update your index so display_category is always an array (even if there is only one item in it). With this the above code will work.

  • Do a check on display_category type and then iterate on it or display it depending of its type. It can be done like this:

    {{#categories.length}}
      {{#categories}}<span class="cat-name">{{.}}</span>{{/categories}}
    {{/categories.length}}
    {{^categories.length}}
      <span class="cat-name">{{categories}}</span>
    {{/categories.length}}
    

Explanation:

Source: https://stackoverflow.com/questions/21545670/how-to-handle-string-or-array-of-strings-in-mustache-template

Wonderful - thank you so much