jekyllliquidliquid-layoutjekyll-extensions

How to pass {% captured %} variable from a view to the layout in Jekyll/Liquid?


I am trying to rebuild a blog in Jekyll and I have stubled upon a simple task.

Provided I have the following set of templates:

default.html:

{{ head }}

{{ content }}

frontpage.html:

---
layout: default
---

{% capture head %}
  Frontpage
{% end %}

{{ content }}

index.html:

---
layout: frontpage
---

Other stuff

I was expecting that {% capture head %} would pass a variable to layout. But it seems only variables from the Front Matter are actually being passed as page.variable_name.

Is there a way to pass capture-d var to the layout in Jekyll?

Guess I could make 2 different layouts for frontpage and normal_page that would replace the whole {{head}}{{content}} block in the layout. But that's like twice the html, so I'd rather solve it with capture if possible.


Solution

  • You can't do this with a capture, but you can using an include. Every level of the page hierarchy can override the head key to point to a different include file as required. This example wraps the include with a condition so if no head key is specified the page will still generate.

    default.html

    {% if page.head %}
      {% include {{ page.head }} %}
    {% endif %}
    
    {{ content }}
    

    frontpage.html

    ---
    layout: default
    head: header1.html
    ---
    
    {{ content }}
    

    _includes/header1.html

    (Frontpage header content)