0

we have this code in template.theme but when we go to view the web, the page show a error as this: "isEven" is an invalid render array key /web/core/lib/Drupal/Core/Render/Element.php . I dont understand very good Drupal and as works it.

function fcjc_bootstrap_preprocess_paragraph(&$variables)
{
  /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
  $paragraph = $variables['paragraph'];
  if ($paragraph->getType() === 'image_text_full_width' || $paragraph->getType() === 'imaxe_texto_biografia_') {
    $variables['isEven'] = $variables['elements']['isEven'];
  }
}


function fcjc_bootstrap_preprocess_field__field_image_text_section(&$vars)
{
  foreach ($vars['items'] as $delta => &$item) {
    $classname = ($delta % 2 == 0 ? 'even' : 'odd');
    $item['attributes']->setAttribute('class', $classname);
    $item['content']['isEven'] = ($delta % 2 == 0);
    }
}

In paragraph.twig I have this: <div class=" image col-sm-4 col-xs-12 {% if isEven %}right-shadow{% else %}left-shadow col-sm-push-8{% endif %}">

Can Somebody can help me? please. Thx

3
  • 4
    It's probably this line $item['content']['isEven'] = ($delta % 2 == 0); you're adding something into the $item['content'] render array which isn't renderable
    – Leigh
    Commented Nov 17, 2020 at 15:24
  • It's a paragraph with diferent content. Inside this parapraph there are image and text block. With this code we want to add differents classes if is even or odd to all paragraphs in template.twig when page is loaded.
    – Adrián
    Commented Nov 18, 2020 at 13:37
  • Are you intentionally overwriting $item['content']['isEven'] with a single value? If so, it might be better to define isEven as a property, so that it is written as $item['content']['#isEven']. You can add any arbitrary properties to a render array.
    – Beau
    Commented Nov 19, 2020 at 15:42

1 Answer 1

0

It's what @Beau wrote in the comment. You have to put a # in the array key.

The code should be:

function fcjc_bootstrap_preprocess_paragraph(&$variables)
{
  /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
  $paragraph = $variables['paragraph'];
  if ($paragraph->getType() === 'image_text_full_width' || $paragraph->getType() === 'imaxe_texto_biografia_') {
    $variables['isEven'] = $variables['elements']['#isEven'];
  }
}


function fcjc_bootstrap_preprocess_field__field_image_text_section(&$vars)
{
  foreach ($vars['items'] as $delta => &$item) {
    $classname = ($delta % 2 == 0 ? 'even' : 'odd');
    $item['attributes']->setAttribute('class', $classname);
    $item['content']['#isEven'] = ($delta % 2 == 0);
    }
}

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.