Howto: Delimiter separated tags

It is possible, but it is a little…unconventional. You have to apply around. This is what I use in cabaret for my tag list.

<!-- layouts/partials/post/tag/list.html -->
{{ with .Params.tags }}
<div class="tags-list">
  <span class="dark-red">Tags</span><span class="decorative-marker">//</span>
  {{ $sort := sort . }}
  {{ $links := apply $sort "partial" "post/tag/link" "." }}
  {{ $clean := apply $links "chomp" "." }}
  {{ delimit $clean ", " }}
</div>
{{ end }}

This block:

  1. Sorts .Params.tags and assigns it to $sort.

    sort .Params.tags => sort [ c, a, b ] => [ a, b, c ]
    
  2. Applies the function partial over the elements of $sort and assigns the resulting list to $links. The partial function is given post/tag/link as the name of the partial to use, and "." is the placeholder for the current element during function application.

    apply [ a, b, c ] "partial" "post/tag/link" "." => [
      partial "post/tag/link" "a",
      partial "post/tag/link" "b",
      partial "post/tag/link" "c",
    ] => [
      <a class="post-tag post-tag-a" href="/tags/a">a</a>\n,
      <a class="post-tag post-tag-b" href="/tags/b">b</a>\n,
      <a class="post-tag post-tag-c" href="/tags/c">c</a>\n,
    ]
    
  3. Removes the trailing \n from each resulting link in $links by applying chomp over the elements and assigning it to $clean.

    apply [ <a…>a</a>\n, <a…>b</a>\n, <a…>c</a>\n ] "chomp" "." => [
      <a class="post-tag post-tag-a" href="/tags/a">a</a>,
      <a class="post-tag post-tag-b" href="/tags/b">b</a>,
      <a class="post-tag post-tag-c" href="/tags/c">c</a>,
    ]
    
  4. Creates a single result by delimiting $clean with ", "; this is inserted as the tag list.

    delimit [ <a…>a</a>, <a…>b</a>, <a…>c</a> ] ", " =>
        "<a…>a</a>, <a…>b</a>, <a…>c</a>"
    

Like I said, it’s a little unconventional, and it requires a little bit of preparatory work to make it sensible, but it’s quite powerful.

<!-- layouts/partials/post/tag/link.html -->
<a class="post-tag post-tag-{{ . | urlize }}" href="/tags/{{ . | urlize }}">{{ . }}</a>
1 Like