Use contains in if statement in Liquid

The contains operator checks if something is present in array or string.

I tend to use this to make specific prechecks. Consider a page builder CMS where you can add sections.

Because you want and need to have an H1 element per page, as a developer you want to make sure the outputted HTML contains this title tag.

I've devised a solution that incorporates a fallback header for pages lacking explicitly set headers or featuring a first section categorized as a header. This approach ensures that if the initial section qualifies as a 'header section,' the presence of an H1 tag is already guaranteed.

Example:

{%- assign detailHeaderTypes = 'article,job_posting,agenda_item' | split: ',' -%}
{%- if post.is_index == false and detailHeaderTypes contains post.content_type.name -%}
{% include 'includes/headers/detail_header', header: post %}
{%- elsif post.page_header != blank -%}
{% include 'includes/headers/page_header', header: post.page_header.first %}
{%- elsif post.content_type.name == 'project' and post.is_index == false -%}
{% include 'includes/project_header' %}
{% else %}
{%- comment -%}
For all pages where no explicit header is set, we use the default header. But only if the first section is not an header (kind of) section.
{%- endcomment -%}
{%- assign headerSectionTypes = 'header_entries_section,header_images_section' | split: ',' -%}
{%- unless headerSectionTypes contains post.sections.first.content_type.name -%}
<header class="default-header">
<h1 class="fallback-title">{{ post.title }}</h1>
</header>
{%- endunless -%}
{%- endif -%}

In this example I actually use contains two times. First for basic article (type) pages like:

  1. article
  2. job_posting
  3. agenda_item

And then later the section type check:

  1. header_entries_section
  2. header_images_section

These are the machine names of these objects.

I like this setup because it either uses the specific headers or in else clause check if the first piece of content, the first section, on the page is 'header-like'. If not, use the fallback header by using unless.

That's it! Hope this helps you.