alex-phillips
alex-phillips

Reputation: 868

List of Dynamic Links in Jekyll

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

Answers (2)

David Jacquel
David Jacquel

Reputation: 52789

Edited answer :

Two problems here :

Generating an empty array in jekyll

{% 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 :

  1. set an empty_array: [] in _config.yml and use it like this : {% assign tag_array = site.empty_array %}

or

  1. create an array "on the fly" with : {% assign tag_array = "" | split: "/" %}

{{ tag_array | inspect }} now returns [].

String concatenation in jekyll

{% 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 :

  1. prepend or append liquid filter like {% assign link = '<a href="/tag/' | append: tag | append: '">' | append: tag | append: '</a>' %}

  2. replace filter like this : {% assign link_template = '<a href="/tag/%%placeholder%%">%%placeholder%%</a>' %} {% assign link = link_template | replace: "%%placeholder%%", tag %}

  3. 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

marcanuy
marcanuy

Reputation: 23942

  • Update

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

Related Questions