Ian
Ian

Reputation: 1166

How to use a variable included in a layout in posts using that layout?

Consider the following three snippets from the specified files:

<!-- _includes/my_var.html -->
{% assign my_var = 'foo' %}

and

<!-- _layouts/default.html -->
{% include my_var.html %}
...

and a post:

---
layout: default
---
I'd like to reference {{my_var}}

The last one doesn't appear to see the variable defined in the includes file. I get nil as the value of my_var. Am I wrong to expect that it should be in scope? If so, what's an alternative approach?

Upvotes: 1

Views: 56

Answers (2)

David Jacquel
David Jacquel

Reputation: 52829

You cannot get layout variables from page or post.

But, as it looks like a configuration variable, you can set it in _config.yml and access it from anywhere with site.my_var.

Upvotes: 1

Goyllo
Goyllo

Reputation: 331

You can do that with frontmatter as well.

---
layout: default
myvar: foo
---
I'd like to reference {{page.myvar}} OR
I'd like to reference {{post.myvar}}

Upvotes: 1

Related Questions