# How to write a segment that is not two other segments

How can I write:

• is segment 3, and is not itemA and is not itemB?
• both itemA and itemB are segment 3 as well.

 {% if craft.app.request.getSegment(3) and craft.request.getSegment(3) !== 'itemA' and craft.request.getSegment(3) !== 'itemB' %} 

To clarify, I want to target a category that is segment 3, but I want to omit two other categories that are on the same segment(level):

• Topics Category
• Subcategory
• Subcategory
• itemA(omit)
• itemB(omit)
• itemC(yes)
• itemD(yes)

In code, I want to achieve this:

{% if craft.request.getSegment(2) == 'Subcategory' %}
// do something
{% elseif craft.app.request.getSegment(3) and craft.request.getSegment(3) !== 'itemA' and craft.request.getSegment(3) !== 'itemB' %}
// do other stuff
{% else %}
// do a generic thing
{% endif %}

• I'm not following... how can segment 3 be both not itemA and not itemB as well as be in segment 3? – Brad Bell Nov 14 '17 at 21:50
• @Brad I think he wants to test if segment 3 is actually set (not empty) but it should not be 'itemA' and not 'itemB' so the condition should be true if the segment is 'itemC'. His explanation is a little bit confusing, I suppose he just wants to tell us that the segment could be 'itemA' or B but the condition should not become true then – Robin Schambach Nov 14 '17 at 21:55

I personally try to avoid inlining too many conditionals because I feel like it leaves room for logical loopholes. I also think using variables for segments keeps things easier to read.

{% set seg2 = craft.request.getSegment(2) %}
{% set seg3 = craft.request.getSegment(3) %}


So maybe something like this? The keyword in is Twig's way of checking in_array()

{% set badItems = ['itemA', 'itemB'] %}

{% if seg2 == 'Subcategory' %}
// do top priority thing
{% elseif seg3 != '' and seg3 not in badItems %}
// do secondary thing
{% else %}
// do overall default thing
{% endif %}


However, if you know the finite list of acceptable items beforehand, I think this is more concise. Since segment 3 could be blank if it's not there, maybe try checking if it is something instead of if it's not something.

{% set goodItems = ['itemC', 'itemD'] %}

{% if seg2 == 'Subcategory' %}
// do top priority thing
{% elseif seg3 in goodItems %}
// do secondary thing
{% else %}
// do overall default thing
{% endif %}

• I like everything about this. The thought process and structured approach. – TRIM Nov 15 '17 at 21:00
• Thanks! Yeah I went years overlooking that in keyword in Twig, but it's so helpful since so much of programming deals with arrays. – Ryan Nov 15 '17 at 23:28