11ty Error: Cannot use "in" operator to search for "y" in unexpected types. (via Template render error)

11ty Error: Cannot use "in" operator to search for "contentwarning" in unexpected types. (via Template render error)

11ty returns this error when I try to make a nunjucks conditional.


Hi I’m trying to add a conditional where if a section of the files frontmatter has contentwarnings: in it, it will make a <details> tag holding a list of all items under that section (in contentwarnings) in a list, and if it doesn’t it doesn’t make it.

Example of what my goal is:
markdown frontmatter:

---
contentwarnings:
  - depictions of violence
  - blood
  - black cats
---

html:

<!--html below will render since contentwarnings is in the frontmatter-->
<details>
<summary>Content warning:</summary>
<ul>
  <li>insert scary thing</li>
  <li>another scary thing</li>
</ul>
</details>

I’m trying to search for the solution for this, I thought I simply messed up the syntax and tried to fix it be removing post.data.contentwarnings as well as renaming the frontmatter and template syntax from content-warning to contentwarning. those didn’t work. Do I need to make this section of nunjucks code into an include?

Below shows the code that I’m having issues with. I know this part’s the part that I’m having issues with since hiding this section and running the command npm start has it working fine.

The code:
the problem code in my template file (nunjucks file):

{% if 'contentwarning' in post %}
          <details>
            <ul>
            {% for contentwarning in contentwarnings %}
            <li>
              {{ contentwarning }}
            </li>
            {% endfor %}
            </ul>
          </details>
{% endif %}

markdown file (for reference):

---
title: content warning test
summary: a test page to test if content warnings could work.
tags: 
  - test
  - content warnings
rating: mature
contentwarnings:
  - depictions of violence
  - blood
  - pog
---

a test page to test if content warnings could work.

I apologize if the answers very simple, I haven’t worked on my site for a while so I’m pretty rusty.

I think you want the first line to be:

{% if (contentwarnings) %}

Not sure if that fixes it fully, but it seems to match the error you’re getting?

2 Likes

That worked thank you! :meow_cheer:

screenshots

image

2 Likes

Yay, glad I could help!

I’ve been learning Eleventy as I build my site, and figuring out how to refer to front matter data is a struggle. :sweat_smile: