2

I have a field I'm pulling into a block twig template block--block-03.html.twig, and it outputs fine by itself (= {{content.field_content_side}}). But when I put it inside of a conditional it is not working.

Here's my code to illustrate what I mean:

<h1>{{ content.field_content_side }}</h1>
<h2>{% if content.field_content_side == 'left' %}col-sm-push-7{% else %}wtf{% endif %}</h2>

The output is here:

enter image description here

Why is it recognizing the twig variable correctly as left (= 1st line of my code), but in the conditional it is saying it's not left (= 2nd line of my code)?

2

Because the field is being rendered, which is different than evaluating its value. content.field_content_side is a render array which holds a lot more than just 'value'.

Try:

{% if node.field_content_side.value == 'left' %}

To get this in a block, you would add this to mytheme.theme:

/**
 * Implements hook_preprocess_block().
 * @param $variables
 */
function mytheme_preprocess_block(&$variables) {
  if (isset($variables['elements']['content']['#block_content'])) {
    $variables['block_content'] = $variables['elements']['content']['#block_content'];
  }
}

Then:

{% if block_content.field_content_side.value == 'left' %}
5
  • I updated the question above to indicate its inside of a block twig template, not a node. I tried content.field_content_side.value which did not work either. – erier Mar 29 '18 at 15:46
  • Then you need to add it in. I will update the answer. – Kevin Mar 29 '18 at 15:47
  • content.field_content_side.value is never going to work from a render array. – Kevin Mar 29 '18 at 15:49
  • you are a life saver. I dont entirely understand what the preprocess function is doing here, but it works and has saved me lots of time. Thank you! – erier Mar 29 '18 at 15:54
  • 1
    It is basically appending the field data in to the block so it is available in the template, similar to having access to the node object in a node template hence the initial if node.field_content_side.value == 'left'. So block_content is the block object and fields. Render arrays can't be used that way, and its one of the things many people run into when trying to do something like this. – Kevin Mar 29 '18 at 15:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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