Reputation: 868
I'm trying to take a posts tags and generate a comma-separated list of their links but can't seem to figure out how to accomplish it. Below is what I have, maybe I'm not using Jekyll's arrays correctly?
{% assign tag_array = [] %}
{% for tag in post.tags %}
{% assign tag_array = tag_array | push: '<a href="/tag/{{tag}}">{{tag}}</a>' %}
{% endfor %}
{{ tag_array | join: ', ' }}
Upvotes: 1
Views: 898
Reputation: 52789
Edited answer :
Two problems here :
{% assign tag_array = [] %}
does nothing.
{{ tag_array | inspect }}
returns nil
, and pushing (like {% assign tag_array = tag_array | push: 'anything' %}
) in nil
always returns nil
.
In order to get an empty array you can :
empty_array: []
in _config.yml and use it like this : {% assign tag_array = site.empty_array %}
or
{% assign tag_array = "" | split: "/" %}
{{ tag_array | inspect }}
now returns []
.
{% assign link = <a href="/tag/{{tag}}">{{tag}}</a> %}
doesn't work in liquid. {{ link | inspect }}
returns nil
.
If you want to concatenate a string, you can use :
prepend
or append
liquid filter like {% assign link = '<a href="/tag/' | append: tag | append: '">' | append: tag | append: '</a>' %}
replace
filter like this :
{% assign link_template = '<a href="/tag/%%placeholder%%">%%placeholder%%</a>' %}
{% assign link = link_template | replace: "%%placeholder%%", tag %}
capture
tag like this : {% capture link %}<a href="/tag/{{ tag }}">{{ tag }}</a>{% endcapture %}
And this now works :
{% assign tag_array = "" | split: "/" %}
{% for tag in post.tags %}
{% capture link %}<a href="/tag/{{ tag }}">{{ tag }}</a>{% endcapture %}
{% assign tag_array = tag_array | push: link %}
{% endfor %}
{{ tag_array | join: ', ' }}
Upvotes: 1
Reputation: 23942
Iterate over the for loop, generating a comma if it is not the last iteration, and capture the output:
{% capture tagscommas %}
{% for tag in page.tags %}
<a href="/tag/{{tag}}">{{tag}}</a>
{% unless forloop.last %},{% endunless %}
{% endfor %}
{% endcapture %}
{{tagscommas}}
If you want to avoid the output with line breaks just put all the code in one line until jekyll uses the new {%- tag that doesn't generate blank lines.
If you don't mind having the output in a variable, just use the inner for
loop to display the links directly as you traverse the tag array.
Upvotes: 2