J Doey
J Doey

Reputation: 43

Sub templates inside of Jekyll

Is there an equivalent to laravel's @section('') blocks in jekyll? What I am trying to do is create a template that can condense the html shared between multiple jekyll pages. For example:

default_layout

<html>
    <div class="page-content">
      <div class="wrapper">
        {{ content }}
      </div>
    </div>
</html>

page_1

---
layout: default
permalink: xxx 
---
<head>
    <title>My title</title>
 {% include header.html %}
 ...
 <div> <!-- A shared block between pages with different content --> </div>
 ....
 <div> <!-- Another shared block between pages with different content --> </div>
 {% include footer.html %}
 </html>

It looks like the current offering of jekyll allows you to use sub-templates, but limits the {{content}} block to be a separate file that also inherits the child template. I would need to create a bunch of files that inherent one another to create the final html page (or so I think).

What worked for me in Laravel was using multiple @yield and @section statements to easily insert dynamic data into a shared template. I don't think Jekyll can do this without creating a bunch of nested sub templates, but I hope I am wrong.

Upvotes: 3

Views: 871

Answers (1)

Christian Specht
Christian Specht

Reputation: 36431

Solution 1:

You could use Jekyll's include files for that.

You probably already know about includes, because you're using them in the layout file in your question.

If your shared blocks are just HTML, using an include is all you need.

But maybe (I'm not sure) the shared blocks are text, meaning you'd like to use Markdown for formatting?

By default, Jekyll doesn't render Markdown in include files, but with a little trick it's still possible to include Markdown files.

I have a site where I needed the same block of text (with formatting and links) on multiple pages, so I did this:

  1. Put the text in a Markdown file into the _includes folder, e.g. _includes/info.md

  2. Include that file and render the Markdown by capturing it and then using the markdownify Liquid filter:

    {% capture tmp %}{% include info.md %}{% endcapture %}
    {{ tmp | markdownify }}
    

Solution 2:

If the shared blocks are the same for certain groups of pages, maybe you want to use multiple layout files.

The best example of this would be a blog built with Jekyll:

You have a "basic" layout (navigation, sidebar, footer...) that all pages share, and which is directly used by "regular" pages.

Then, you have a second layout "inheriting" from the main one, which adds stuff like post date, tags and so on - this is used by all blog posts.

Here's a simple Jekyll example for this.

Upvotes: 1

Related Questions