Score:0

Pass current langage to twig on custom blocks

za flag

my custom module block, with supposely no cache

<?php

namespace Drupal\amu_social_icon\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Icon' Block
 *
 * @Block(
 *   id = "amu_social_icon_block",
 *   admin_label = @Translation("Social Icon block"),
 * )
 */
class IconBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $config = \Drupal::config('amu_social_icon.settings');
    return [
      '#theme' => 'amu_social_icon_block',
      '#icons' => $config->get('amu_social_icon_icons'),
      '#attached' => [
        'library' => [
          'amu_social_icon/global-styling',
        ],
      ],
    ];
  }

  /**
   * @return int
   */
  public function getCacheMaxAge() {
    return 0;
  }
}

the language context i am trying to add on internal urls

<ul class="social-icon menu socialicon-nav">
      {{ dump(language) }}
  {% for icon in icons %}
    {% if icon.url is not empty %}
          {% if icon.url starts with '/' %}
                <li><a href="/{{ language }}{{ icon.url }}" aria-label="{{ icon.aria_label }}"><i aria-hidden="true" class="{{ icon.icon }}"></i></a></li>
          {% else %}
                   <li><a href="{{ icon.url }}" aria-label="{{ icon.aria_label }}"><i aria-hidden="true" class="{{ icon.icon }}"></i></a></li>
    {% endif %}
      {% endif %}
  {% endfor %}
</ul>

i understood the variable passed by hook_theme are static so i have tried to override it on preprocess block

function amu_social_icon_theme($existing, $type, $theme, $path) {
  return [
    'amu_social_icon_block' => [
      'variables' => [
        'icons' => null,
        'language' => \Drupal::languageManager()->getCurrentLanguage()->getId()
      ],
    ],
  ];
}

function amu_social_icon_preprocess_block(&$vars) {
  if ($vars['plugin_id'] == 'amu_social_icon_block') {
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $vars['language'] = $language;
  }
}

None of these works. I need to empty drupal cache so that

{{ dump(language) }}

display the correct current language

Score:3
cn flag

I understood the variable passed by hook_theme are static

Yes, you can consider default values defined in hook_theme as static, they are set when you install the module. To help developers clearing the cache also clears most things which are installed by modules, so that you don't need to re-install the module all the time, but this has nothing to do with render caching.

language is a variable of your custom theme, not of the block. Then you don't need a preprocess hook, you can add it directly to the block build containing this template:

  public function build() {
    return [
      '#theme' => 'amu_social_icon_block',
      '#language' => $language,

Caching of the current language works out-of-the-box. This is one of the three default contexts. However, you can't debug caching by debug output. Most times you have a cache hit, serving the content from cache, without running the code building the content.

Matoeil avatar
za flag
this causes User error: "language" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).
4uk4 avatar
cn flag
I've added a `#` sign before the variable name .
sonfd avatar
in flag
Does every render array vary by language by default? That's what your answer seems to imply. Looking at OP's code, it doesn't look like the block is actually a translated entity. Won't you need to manually add a language cache context to the block?
4uk4 avatar
cn flag
@sonfd, out of the box this is the case for all render arrays. See https://drupal.stackexchange.com/questions/298480/how-do-i-specify-a-render-cache-context-as-universal
Matoeil avatar
za flag
i have tried '#language' => $language but it is null
Score:0
za flag

a default value seems to be needed in hook_theme

 */
function amu_social_icon_theme($existing, $type, $theme, $path) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  return [
    'amu_social_icon_block' => [
      'variables' => [
        'icons' => null,
        'lang' => $language,
      ],
    ],
  ];
}

as well as a #cache entry in the block build method

<?php

namespace Drupal\amu_social_icon\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Icon' Block
 *
 * @Block(
 *   id = "amu_social_icon_block",
 *   admin_label = @Translation("Social Icon block"),
 * )
 */
class IconBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $config = \Drupal::config('amu_social_icon.settings');
    return [
      '#theme' => 'amu_social_icon_block',
      '#icons' => $config->get('amu_social_icon_icons'),
      '#lang' => $language,
      '#cache' => [
        'max-age' => 0,
      ],
      '#attached' => [
        'library' => [
          'amu_social_icon/global-styling',
        ],
      ],
    ];
  }

  public function getCacheMaxAge() {
    return 0;
  }
}
leymannx avatar
ne flag
Drupal calls should be avoided in class, inject dependencies instead. But besides that: nice!
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.