Accessing content variables from template

For the sake of not repeating the same code on every post I encapsulated the posts’ content in a template. But in doing so, I can’t find a way to make the code work because it uses variables I declare in the posts’ Front Matter, for example (not my actual code):

{% if page.count == 10 %}
  {{ page.count }}
{% endif %}

But I’m not able to transfer this logic to my template because I can’t access the count variable, this doesn’t work:


{{ content }}
{% if content.count == 10 %}
  {{ content.count }}
{% endif %}

What can I do in this situation? Do I need to write the piece of code in every post?

Do you have this in a public repo? It would be easier if we could see the code.

{% if page.count == x %} should work fine supposing you have count: x in the frontmatter of the page.

As for template.html, I’m a little confused about what that’s for. If you have a block of code you want to call in a layout or elsewhere, you might try an include. Regardless, I can’t think of a way content.count will work. content is going to pull the body content of a markdown file into a layout or for loop (in typical cases). There is no way to add an object to that.

1 Like

That’s the problem, I could write the {% if page.count == x %} piece of code but then I would have to do this is every post I have, I’m trying to find a better solution for this.

The best thing I got for now is the include one but I still have to write the include line in every post, that’s why I wanted to do in the template, that way I’d just inform the template in the post and the template itself would handle this for me, but I guess that’s not possible.

Anyway, thanks for the include tip, writing one line of code is better than writing a whole paragraph of Liquid.

is the thing you are trying to inject in the middle of the content? or is at at top/bottom? in your example it looks like it would be at the bottom. If that is the case you should be able to do it in a layout no problem - the layout can access page front matter.

How can I access the page front matter from the template? I tried to do {{ content.[variable] }} but that didn’t work for me.

{{page.whatever}} so for you {{page.count}}

so for a blog you can put the date, author name, category etc wherever you want and then the content of the post goes where the content is.

It worked, can’t believe I didn’t try that. Thanks, person!