Search code examples
markdownjekylljekyll-theme

Jekyll: link inside a variable called from a markdown file


I have a series of posts in Jekyll for which I want to have a banner at the bottom with a link to an internal page.

Here's the beginning of my MD post:

---
layout: post
title:  "Title"
date:   2022-12-06 18:26:05 +0100
categories: category
author: Author name
author-pic: author.jpg
banner-bottom: Some test some test some test [Link to a page]({{ site.baseurl | }}{% link page.html %}).
---

In the post layout I'm calling the variable {{page.banner-bottom}} inside a <div>:

{% include header.html %}

        <article>
            <h1>{{ page.title }}</h1>
            <div class="author-name">
                <img src="{{ site.baseurl }}/{{ page.author-pic }}" alt=""><span>{{ page.author }}</span>
            </div>

            {{content}}

            <div class="banner-bottom">{{page.banner-bottom}}</div>

    </article>

{% include footer.html %}

Unfortunately [Link to a page]({{ site.baseurl }}{% link alumni.html %}) is rendered as text and not converted to a link. Any idea why? I also tried escaping site.baseurl like {{ site.baseurl | escape }} with no luck.


Solution

  • This SO post: Custom Variables in Jekyll Front Matter is somehow related but pretty old.

    Here's an idea, actually not my own. I used the solution from this blog post: How to nest template variables inside yaml front matter once.

    The idea is simple:

    1. Create a plugin:

    # file: _plugins/expand_nested_variable_filter.rb
    
    module Jekyll
      module ExpandNestedVariableFilter
        def flatify(input)
          Liquid::Template.parse(input).render(@context)
        end
      end
    end
    
    Liquid::Template.register_filter(Jekyll::ExpandNestedVariableFilter)
    

    2. Apply the filter:

    ---
    layout: post
    title:  "Title"
    date:   2022-12-06 18:26:05 +0100
    categories: category
    author: Author name
    author-pic: author.jpg
    banner-bottom: Some test and [link to a page]({{ site.baseurl }}{% link page.html %}).
    ---
    
    {{ site.baseurl | flatify }}
    

    Jekyll searches links from the root folder, so you maybe need to adjust the path. Jekyll will tell you when your link is not valid :) I ended up testin g with my 404.html page