Help with conditional expression: check if item exists and return different HTML

Describe the problem/error/question

Hi everyone,

I’m working on a workflow in n8n and I need help writing a conditional expression.

What I want to do:
Inside an expression (used in an HTML field), I want to check if a certain item exists — for example, an image coming from an Airtable field. If it exists, I want to generate an HTML link using its filename. If it doesn’t, I want to display a fallback message.

For example:

  • If $('Airtable').item.json['Photo'][0].filename exists, then output something like:
    <a href="logo_url">filename</a>
  • Else, show:
    <span style="color: red;">We don’t have your logo image.</span>

I tried different syntaxes using ternary operators and optional chaining (?.), but I can’t seem to get it working correctly inside an n8n expression.

:warning: Important: I would like to do this directly in the expression, not by using an additional Function or IF node, because I need to repeat this kind of logic in multiple places, and using extra nodes would make the workflow too complex.

Could someone help me write the correct expression for this kind of logic?

Thanks a lot in advance! :folded_hands:

You can do the following:

{{ $('Airtable').item.json['Photo']?.[0]?.filename
? `<a href="https://your-host.com/${$('Airtable').item.json['Photo'][0].filename}">${$('Airtable').item.json['Photo'][0].filename}</a>`
: '<span style="color: red;">We don’t have your logo image.</span>' }}

OR

{{ 
  (() => {
    const file = $('Airtable').item.json['Photo']?.[0]?.filename;
    return file 
      ? `<a href="https://your-host.com/${file}">${file}</a>` 
      : '<span style="color: red;">We don’t have your logo image.</span>';
  })() 
}}

But you should consider the following:

  • Make sure the Photo field is a list and has at least one element before accessing [0].
  • ?. This avoids errors if any part of the path doesn’t exist.
  • Encapsulating it in an anonymous function ( () => {} )() allows you to use variables within the expression.
2 Likes

Thanks a lot it works :slight_smile:
sorry i’m new in n8n ahah

just to know how the “?.” works ?

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.