11ty / eleventy

A simpler site generator. Transforms a directory of templates (of varying types) into HTML.
https://www.11ty.dev/
MIT License
17k stars 491 forks source link

Nunjucks template with multiple content blocks #2611

Open ced64k opened 1 year ago

ced64k commented 1 year ago

I read a few issues to have multiple content blocks in a template but I can't make it work. It's working wiht paired shortcode but I see 'undefined' in the output html in my .content div, I presume at the end of {{ content }}. If I log !this.page.layoutblock it says undefined,

Any idea ? Maybe you have a better option to render multiple content blocks ? Thank you.

.eleventy.js

  eleventyConfig.addShortcode('renderlayoutblock', function(name) {
    return (this.page.layoutblock || {})[name];
  });
  eleventyConfig.addPairedShortcode('layoutblock', function(content, name) {
    if (!this.page.layoutblock) this.page.layoutblock = {};
    this.page.layoutblock[name] = content;
  });

template.njk

<div class="content">
  {{ content | safe }}
</div>
<div class="content2">
  {% renderlayoutblock 'content2' %}
</div>

mypage.njk

---
layout: template.njk
title: "My page"
parameter1: lorem
parameter2: ipsum
parameter3: 3333
---
<h1>Title</h1>
<p>Lorem ipsum</p>
{% layoutblock "content2" %}
    <h2>Title</h2>
    <p>Lorem ipsum</p>
{% endlayoutblock %}
ced64k commented 1 year ago

Nevermind I found 😅 No need adding code in .eleventy.js. The trick was the extends with template name instead of front matter.

template.njk

<div class="content">
   { {% block content1 %}
     This is the content
  {% endblock %}
</div>

<div class="content2">
  { {% block content2 %}
     This is the content 2
  {% endblock %}
</div>

mypage.njk

---
title: "My page"
parameter1: lorem
parameter2: ipsum
parameter3: 3333
---
{% extends 'template.njk' %}

{% block content %}
   <h1>Title content 1</h1>
   <p>Lorem ipsum</p>
{% endblock %}

{% block content2 %}
    <h2>Title content 2</h2>
    <p>Lorem ipsum</p>
{% endblock %}
etherealite commented 3 months ago

A warning to anyone trying this with a layout specified in their front matter.

It will not work, it will break the data cascade and any overrides you have done between your layouts will be erased.