alexcarpenter / alexcarpenter-11ty

📝 Source files for my personal website built with Eleventy and hosted with Netlify.
https://alexcarpenter.me
90 stars 14 forks source link

Conditional template blocks #22

Closed alexcarpenter closed 6 years ago

alexcarpenter commented 6 years ago

Make use of conditional template blocks to create flexible page layouts in Craft CMS.

{% extends '_layouts/default' %}

{% block content %}
  <div class="o-page">
    {% set _sidebar = block('sidebar') %}
    {% if _sidebar is not empty %}
      <section class="o-page__sidebar">
        {% block sidebar %}{% endblock %}
      </section>
    {% endif %}

    <main class="o-page__main">
      {% block main %}{% endblock %}
    </main>
  </div>
{% endblock %}
alexcarpenter commented 6 years ago

In an effort to keep our Craft CMS templates DRY. It is helpful to create a set of layout templates to account for our sites page specific layouts.

A common pattern is a layout area that supports a sidebar alongside our main content. Below is some markup that you might expect.

<div class="container">
    <div class="content">…</div>
    <div class="sidebar">…</div>
</div>

Now let's introduce this page layout into our default layout template.

{% extends '_layouts/default` %}

{% block 'container' %}
    <div class="container">
        <div class="content">
            {% block 'content' %}{% endblock %}
        </div>

        <div class="sidebar">
            {% block 'sidebar' %}{% endblock %}
        </div>
    </div>
{% endblock %}

Now we can start making use of this page layout.

{% extends '_layouts/page' %}

{% block 'content' %}
    <article>…</article>
{% endblock %}

{% block 'sidebar' %}
    <ul>…</ul>
{% endblock %}

Now let's say we have another page, but that page does not have any content that needs to be supported in the sidebar.

// Usage
{% extends '_layouts/page' %}

{% block 'content' %}
    <article>…</article>
{% endblock %}

// Output
<div class="container">
    <div class="content">
        <article>…</article>
    </div>
    // Unused sidebar div
    <div class="sidebar"></div>
</div>

We can see that whether or not we make use of the sidebar block, the sidebar div will always be output on our page. Let's see how we can conditionally make use of the sidebar when needed.

{% extends '_layouts/default` %}

{% block 'container' %}
    <div class="container">
        <div class="content">
            {% block 'content' %}{% endblock %}
        </div>

        {% set _sidebar = block('sidebar') %}
        {% if _sidebar is not empty %}
            <div class="sidebar">
                {% block sidebar %}{% endblock %}
            </div>
        {% endif %}
    </div>
{% endblock %}

Now if our template does not make use of the sidebar, the sidebar div will not be output and our content div can stretch full width using flex: 1;.