Creating a comma separated list of tags

I have an template that is creating tags that are links.
I would like to add commas between the tags.
How can I do this so that the last tag does not have a comma.

<%= for tag <- @video.tags do %>
    <%= link tag.name , to: tag_path(@conn, :show, tag.name) %>,
 <% end %>

Current Output
family, friends, vacation,

Desired Output
family, friends, vacation

# in the view module
def format_tags(conn, tags) do
  tags
  |> Enum.map(fn tag -> link(tag.name, to: tag_path(conn, :show, tag.name) end)
  |> Enum.intersperse(", ")
end

# in the template
<%= format_tags(@conn, @video.tags) %>
8 Likes

And if you actually only want the comma’s to show to users but not in the HTML source (i.e. it is not interesting to SEO bots):

<div class="video_tags">
<%= for tag <- @video.tags do %>
    <%= link tag.name , to: tag_path(@conn, :show, tag.name) %>,
 <% end %>
</div>
.video_tags > a::after {
    content: ", ";
    display: inline;
}
.video_tags > a:last-child::after {
    display: none;
}

Example

7 Likes

I didn’t know you can do this with just CSS. Nice tip :+1:

2 Likes

The same trick is used very commonly for many other things, such as having a different bottom-padding below the last paragraph. :slight_smile:

1 Like

I’m starting to understanding how you can use the view module now.
You can create your list of html tags inside it and then use it in the template. Makes sense.

I always wanted to know what “Enum.intersperse” did. Cool example.

2 Likes

This is has to do with css selectors. I’m gonna spend some time look into this. Really simple solution. Never thought about using CSS

1 Like