Twig/Timber conditional to show body class

2.8k Views Asked by At

I am looking for a way to add a class to the body if there is a particular string in the URL.

I have kind of got the logic working, but the following syntax: 1. Is not DRY 2. Only cycles the first iteration because of the if statement

I think I need to somehow place an array after the 'if' statement, but not sure on the syntax. any help would be appreciated. thanks

{% if 'bus-data' in post.link %}
  <body class="{{body_class}} jumbo" data-template="base.twig">
{% elseif 'bus-data' not in post.link %}
  <body class="{{body_class}}" data-template="base.twig">
{% endif %}

{% if 'taxi-data' in post.link %}
  <body class="{{body_class}} jumbo" data-template="base.twig">
{% elseif 'taxi-data' not in post.link %}
  <body class="{{body_class}}" data-template="base.twig">
{% endif %}

{% if 'education-data' in post.link %}
  <body class="{{body_class}} jumbo" data-template="base.twig">
{% elseif 'education-data' not in post.link %}
  <body class="{{body_class}}" data-template="base.twig">
{% endif %}

{% if 'public-data' in post.link %}
  <body class="{{body_class}} jumbo" data-template="base.twig">
{% elseif 'public-data' not in post.link %}
  <body class="{{body_class}}" data-template="base.twig">
{% endif %}
2

There are 2 best solutions below

0
On BEST ANSWER

It seems I was probably over-complicating something that was quite simple, and walking away from it made it clearer. I just tidied my 'else if' loop:

{% if 'bus-data' in post.link %}
  <body class="{{body_class}} jumbo" data-template="base.twig">
{% elseif 'taxi-data' in post.link %}
  <body class="{{body_class}} jumbo" data-template="base.twig">
{% elseif 'education-data' in post.link %}
  <body class="{{body_class}} jumbo" data-template="base.twig">
{% elseif 'public-data' in post.link %}
  <body class="{{body_class}} jumbo" data-template="base.twig">
{% else %}
  <body class="{{body_class}}" data-template="base.twig">
{% endif %}
1
On

You could create a new filter to solve this,

Filter

$twig->addFilter(new Twig_SimpleFilter('contains', function ($value, $needles) {
    if (!is_array($needles)) $needles = [ $needles, ];
    foreach($needles as $needle) if (strpos($value, $needle) !== false) return true;
    return false;
});

Twig

<body class="{{body_class}}{% if post.link|contains(['bus-data', 'taxi-data', 'education-data', 'public-data',]) %} jumbo{% endif %}" data-template="base.twig">