Hi all!
I've got 2 collections set up in my 11ty project. I want to put out different info on a page if one of those tags comes back as true?
collections.design
collections.dev
Something like ....
{%- if post.data.tags === design -%} Do stuff {%- endif -%}
Is this possible at all from one of the .njk template files?
@aaronstezycki Should work. I cant remember if tags is _always_ an array, or only sometimes, but this worked for me in my _includes/layouts/base.njk file:
{%- if tags and tags.includes("design") -%}
{% include "design-header.njk" %}
{%- endif %}
{%- if tags and tags.includes("development") -%}
{% include "development-header.njk" %}
{%- endif -%}
I needed the initial if tags check because some templates (like my /about-me/ page) didn't have any tags defined, so tags was undefined.
I also have a fictional /posts/design-and-development.njk template which has the following front-matter:
---
title: Design and development page 1
tags:
- design
- development
---
Design and development page 1. Double threat!
And when I build the site it will display both headers, so you might need some more if else..if tweaking if you only want the design header OR the development header to display on a page (but never both).
@pdehaan Thank you very much.
{%- if tags and tags.includes("design") -%}
This worked a treat, and seems pretty robust with the first if tags check you mentioned.
Great stuff :)
@aaronstezycki Not very interesting, but I pushed my sample repo: https://github.com/pdehaan/11ty-1004
I was a bit tired of checking {% if tags %} in 3+ places, so I hacked this in my base layout, which just defaults the tags to an empty array if it is undefined:
{%- set tags = tags or [] -%}
I also moved the conditional logic out of my base template and into an include and went the if..elif route so it only shows the design header or development header.
{%- if tags.includes("design") -%}
{% include "design-header.njk" %}
{%- elif tags.includes("development") -%}
{% include "development-header.njk" %}
{%- endif -%}
Most helpful comment
@aaronstezycki Not very interesting, but I pushed my sample repo: https://github.com/pdehaan/11ty-1004
I was a bit tired of checking
{% if tags %}in 3+ places, so I hacked this in my base layout, which just defaults the tags to an empty array if it is undefined:I also moved the conditional logic out of my base template and into an include and went the
if..elifroute so it only shows the design header or development header.