3
votes

I'm trying to create a jekyll page with all of my posts listed sequentially. The problem is that some posts use different layouts, which are then specified in the post frontmatter. I've disabled individual page output for the posts (actually a custom category), so the layouts are partials.

For example, say I have some red posts and green posts:

_posts/01_post1.md:

---
layout: redpost
---
Post 1 (red)

_posts/02_post2.md:

---
layout: greenpost
---
Post 2 (green)

I want these to get processed using the correct layout. I also would prefer to use inheritance, which I think precludes the use of {%include%}.

_layouts/post.html:

<article class="post">
{{ content }}
</article>

_layouts/redpost.html:

---
layout: post
---
<div style="color:red">
{{ content }}
</div>

Then in my top-level page I want to loop over all the posts, render them using the appropriate template, and concatenate the result. Obviously no RENDER filter exists, although perhaps I was just unable to find it's name in the documentation.

_layouts/index.html:

<html>
...
{% for post in site.posts %}
{{ post | RENDER }}
{% endfor %}
</html>

The desired final HTML would then look like:

<html>
<article class="post">
  <div style="color:red">
    <p>Post 1 (red)</p>
  </div>
</article>
<article class="post">
  <div style="color:green">
    <p>Post 2 (green)</p>
  </div>
</article>
</html>

Is this possible without plugins?

2
What do you mean by inheritance? Other than that, this seems perfectly possible with an include called 'greenpost.html'.JoostS
@JoostS Inheritance is when one layout itself has layout: parentlayout front matter. It lets you make a parent layout with shared headers, footers, etc, while child layouts can customize the content. See learn.cloudcannon.com/jekyll/introduction-to-jekyll-layouts/…Quantum7
@Quantum7 Did you see the source of the Post 1 (red) single post page at sbliven.github.io/jekyll-template-inheritance/jekyll/update/… ? It's an invalid HTML because your _layouts/post.html layout does not include a HTML DOCTYPE, html tag, head and body, etc.Alex Vang
@AnAurelian good point. I was only worrying about getting the homepage (sbliven.github.io/jekyll-template-inheritance) to render correctly. I don't know if there's a way to render a post using a different layout in different contexts.Quantum7

2 Answers

3
votes

The solution was trivial, which is why it isn't mentioned in the documentation. A document object gets rendered with the correct template just by being printed directly:

{% for post in site.posts %}
  {{ post }}
{% endfor %}
1
votes

What is wrong with the following? Seems like a solution to me.

_layouts/index.html:

<html>
...
{% for post in site.posts %}
    {% include post.html %}
{% endfor %}
</html>

_includes/post.html:

<article class="post">
  {% if post.layout == 'greenpost' %}
    {% include greenpost.html %}
  {% endif %}
</article>

_includes/greenpost.html:

<div style="color:green">
  {{ post.content }}
</div>