twigdrupal-8drupal-blocksdrupal-templates

Drupal 8 - Twig template won't get variables values


I'm trying to make a twig template to get a variable from a custom block, when I do a {{ dumb() }} it shows me the variables and their values but when I call for the variable it won't show it, even when i call the variable with dumb {{ dumb(title) }} it tells me is NULL. Could anyone help me understand what is the mistake?

Block: onyx_experiencia.php

/**
 * Provides a 'Test' Block.
 *
 * @Block(
 *   id = "onyx_experiencia",
 *   admin_label = @Translation("Servicios OnyxGroup"),
 *   category = @Translation("Servicios OnyxGroup"),
 * )
 */
class onyx_experiencia extends BlockBase implements BlockPluginInterface {

 /**
   * {@inheritdoc}
   */  
  public function build() {
      $title = 'TestTitle34';
      $desc = 'Test text 24';
      $test_array = array(
            '#title' => $title,
            '#description' => $desc
        );

      return $test_array;

  }

block.module: onyx_experiencia.module

<?php
/**
 * Implements hook_theme().
 */
function onyx_experiencia_theme($existing, $type, $theme, $path) {

    return array(
        'block__serviciosonyxgroup' => array(
            'template' => 'block--serviciosonyxgroup',
            'render element' => 'elements',
            'variables' => array(
                'title' => 'TitleTest',
                'description' => 'DescriptionTest'
            ),
        ),
    );
}

Twig File: block--serviciosonyxgroup.html.twig

{#
/**
 * @file
 * Profile for onyx_experiencia block.
 */
#}

<h3>Featured Events</h3>
<p>Test: {{ title }} </p>
<p>Test: {{ description }} </p>

<ol>
  {% for key, value in _context  %}
    <li>{{ key }}</li>
  {% endfor %}
</ol>

{{ dump(content) }}

Result: This is the result i get enter image description here

UPDATE Different way still not working

enter image description here


Solution

  • As seen on your screenshot:

    The variables live in the variable content, not in _context
    Your current template code assumes they in live _context though as they aren't prefixed with anything.

    {{ title }} equals <?= isset($_context['title']) ? $_context['title'] : null; ?>

    So u'd need to change the template to something like

    <h3>Featured Events</h3>
    <p>Test: {{ content['#title'] }} </p>
    <p>Test: {{ content['#description'] }} </p>