DEV Community

Robert Rees
Robert Rees

Posted on

How to use Jekyll's link tag with data values

Jekyll's link tag is one of the gems of Jekyll for me. It makes it almost impossible to create broken links. However until recently I was not sure how to combine it with data values either from data files or from front matter. It wasn't clear to me how identities were resolved. The good news is that for the most part these work exactly as you might hope and you should always be to pass a reference to a data value to the tag and have it resolve during the build as you would expect.

My first case was a data-file driven navigation bar where depending on the categories a post has I want to select a navigation root item. The relevant categories are simply keys in a data file with the path to the navigation root and the display name for the link being the value. The code is below and the only thing worth commenting on is that the assign makes the data lookup clean and gives a simple name to reference the fields in the structure that has been found.

    {% for category in page.categories %}
    {% if site.data.navigation contains category %}
    {% assign navigation = site.data.navigation[category] %}
    <p><a href="{% link {{navigation.path}} %}">{{navigation.name}}</a></p>
    {% endif %}
    {% endfor %}
Enter fullscreen mode Exit fullscreen mode

My other use case is similar, where I want pages to link back to a root or core page I want to be able to describe the name and path of the page in my front matter. The link is then part of an include that has a conditional check on the top-level front matter key existing.

{% if page.hub_page %}
<p> Part of <a href="{% link {{page.hub_page.path}} %}">{{page.hub_page.name}}</a></p>
{% endif %}
Enter fullscreen mode Exit fullscreen mode

This is much simpler than the previous example and better illustrates how tags and variable substitution can be combined.

Top comments (0)