Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jekyll - Can't Access Custom Front Matter Variables

I am new to Jekyll and would like to create additional variables in a Post Frontmatter:

style:
  name: post
img: image_name

When I try to use a variable like title it works

{% page.title %}

But when I try to use another variable

{% if page.img %}
  {{ page.img }}
{% else %}
  No image
{% endif %}

That returns nil. Even when simply trying to output

{{ page.img }}

Any idea why I can't use my custom variables defined in the frontmatter?

like image 587
stefano_cdn Avatar asked Apr 15 '16 17:04

stefano_cdn


People also ask

Why do I need to set global variables in Jekyll?

The set of triple-dashed lines with nothing in between will still get Jekyll to process your file. (This is useful for things like CSS and RSS feeds!) There are a number of predefined global variables that you can set in the front matter of a page or post. If set, this specifies the layout file to use.

What is front matter in Jekyll?

Front Matter Any file that contains a YAML front matter block will be processed by Jekyll as a special file. The front matter must be the first thing in the file and must take the form of valid YAML set between triple-dashed lines. Here is a basic example:

How do I create a front matter in YAML?

The front matter must be the first thing in the file and must take the form of valid YAML set between triple-dashed lines. Here is a basic example: --- layout: post title: Blogging Like a Hacker --- Between these triple-dashed lines, you can set predefined variables (see below for a reference) or even create custom ones of your own.

Why won't Jekyll load a file without a layout file?

This is overridden if the file is a post/document and has a layout defined in the front matter defaults . Starting from version 3.5.0, using none in a post/document will produce a file without using a layout file regardless of front matter defaults. Using none in a page will cause Jekyll to attempt to use a layout named "none".


2 Answers

After some research I discovered that my YAML FrontMatter variables were not read inside a layout file, and found this link:

https://github.com/jekyll/jekyll/issues/4123

So I changed

{{ page.img }}

to:

{{ layout.img }}

and now it works.

like image 88
stefano_cdn Avatar answered Sep 18 '22 18:09

stefano_cdn


You should use {{ page.img }} instead of {% page.img %}. The percents in {% %} are usually for when you are doing something other than just calling a variable - like if statements, for statements, includes etc.

I wouldn't think {% page.title %} would work on its own.

like image 34
Ron Avatar answered Sep 17 '22 18:09

Ron