3

This evaluates to false

{% if block.imageWidth starts with block.imageWidth %}

But this evaluates to true

{% if '{{ block.imageWidth }}' starts with '{{ block.imageWidth }}' %}

Some sort of issue with Craft's Twig integration?

1 Answer 1

3

I'm going to assume that your imageWidth field is a dropdown menu... correct me if I'm wrong. When you output a dropdown fieldtype in your templates, it's an object, not a string.


Scenario 1: Comparing objects

{% if block.imageWidth starts with block.imageWidth %}

The starts with comparison operator is designed for strings, but here it's handling two objects. Makes sense that it would just give up and evaluate to false.

Scenario 2: Comparing strings

{% if '{{ block.imageWidth }}' starts with '{{ block.imageWidth }}' %}

In Twig, you can't nest tags. Those strings are being read literally, and not parsed out into their respective values. So what you've got here is a comparison of two identical strings... Makes sense that this would evaluate to true.

Scenario 3: Comparing values

{% if block.imageWidth.value starts with block.imageWidth.value %}

Working under the assumption that imageWidth is a dropdown menu, then you are actually getting an object from block.imageWidth. Twig isn't confident that you actually want a string here, so you'll need to append .value to specifically get the value of your field.


I've seen this trip up a few people, but it makes perfect sense once you wrap your head around it. Many objects in Craft will try to automatically "stringify" themselves when output directly using curly braces. But when it's not a direct output tag, you'll generally need to tell Twig that you specifically want the string value, and not the object itself.

2
  • 1
    Great answer, everything is working fine now (and I learned!)
    – kai
    Commented Feb 3, 2016 at 5:58
  • Excellent, happy to help! :)
    – Lindsey D
    Commented Feb 3, 2016 at 5:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.