Moshe
Moshe

Reputation: 7007

Two Ternary Operators in One Twig Statement

I am using two different ternary operators to conditionaly add classes using twig. Here is what my code looks like:

class="topbar-links {{ dropdown ? 'topbar-links__dropdown' }} {{ cta ? 'topbar-links__cta' }}"

I am wondering if it is really necessary for me to close the first ternary statement with ending curly brackets and then immediately start a new ternary statement with opening curly brackets. Is there some way to combine this in one statement? Perhaps something like this:

class="topbar-links {{ dropdown ? 'topbar-links__dropdown', cta ? 'topbar-links__cta' }}"

Now this does not work - but it's the type of thing I am looking for. In short, some way to simplify the code. Is something like this possible? If so, how?

Thanks.

Upvotes: 0

Views: 246

Answers (2)

ffx14
ffx14

Reputation: 2104

You can achieve this with

class="topbar-links{{ (dropdown ? ' topbar-links__dropdown') ~ (cta ? ' topbar-links__cta') }}"

Upvotes: 2

DarkBee
DarkBee

Reputation: 15594

One way of doing it would be to populate an array I guess

class="topbar-links {{ [ topbar ? 'topbar-links__dropdown', cta ? 'cta-links__dropdown', ]|filter(v => v)|join(' ') }}"

demo

Upvotes: 1

Related Questions