user39063
user39063

Reputation: 315

Jekyll / Liquid include files dynamically

currently I'm working on a new site with Jekyll and have some kind of problem there. I have a layout page, where I can define the background image with variables from each page.

Layout:

class="background background-{{ page.header_bg }}"

Page:

---
header_bg: storm
---

But now I want to include some file dynamically, depending on the variable value. Well, I can do it with some if or case statements, but actually I want to do something like

{% include page.header_bg %}

But this does not work, because Jekyll is looking for a file, that is called "page.header_bg" and not the value.

Can some one help me please?

Upvotes: 5

Views: 4186

Answers (2)

James Jones
James Jones

Reputation: 8763

I know this question is 6 years old but here's a clear answer for posterity. You need to assign page.header_bg to a variable first and then use the variable in the include statement.

{% assign headerBg = page.header_bg %}

{% include headerBg %}

You will get an error Liquid Exception: Invalid syntax for include tag if you attempt to use page.header_bg directly in the include statement.

Upvotes: 0

Christian Specht
Christian Specht

Reputation: 36421

According to the docs, you need to put the variable name inside additional {{ }}.

Quote from the link:

ProTip™: Use variables as file name

The name of the file you wish to embed can be literal (as in the example above), or you can use a variable, using liquid-like variable syntax as in {% include {{my_variable}} %}.

Upvotes: 12

Related Questions