Browse Source

Issue #3313874: Add ability to evaluate conditions like the block visibility settings

merge-requests/17/head
Rodrigo Aguilera 3 years ago
parent
commit
974250392a
  1. 9
      docs/cheat-sheet.md
  2. 33
      src/TwigTweakExtension.php

9
docs/cheat-sheet.md

@ -351,6 +351,15 @@ ensure that cache metadata are bubbled up.
{{ content.field_media|cache_metadata }}
```
## Conditions from context
The system that controls the visibility of blocks can be used to evaluate
if a condition is fullfilled.
```twig
{% if languageIsSpanish = drupal_condition_evaluate('language', {'langcodes': {'es':'es'}}) %}
Hola
{% endif %}
```
## PHP
PHP filter is disabled by default. You can enable it in `settings.php` file as
follows:

33
src/TwigTweakExtension.php

@ -86,6 +86,8 @@ class TwigTweakExtension extends AbstractExtension {
new TwigFunction('drupal_breakpoint', [self::class, 'drupalBreakpoint'], $all_options),
// @phpcs:ignore Drupal.Arrays.Array.LongLineDeclaration
new TwigFunction('drupal_contextual_links', [self::class, 'drupalContextualLinks']),
// @phpcs:ignore Drupal.Arrays.Array.LongLineDeclaration
new TwigFunction('drupal_condition_evaluate', [self::class, 'drupalConditionEvaluate']),
];
$this->moduleHandler->alter('twig_tweak_functions', $functions);
@ -420,6 +422,37 @@ class TwigTweakExtension extends AbstractExtension {
return $build;
}
/**
* Use a condition plugin to evaluate based on the context.
*
* @param string $plugin_id
* The plugin ID.
* @param array $configuration
* Configuration for the plugin.
*
* @return bool
* The evaluation of the plugin.
*/
public static function drupalConditionEvaluate(string $plugin_id, array $configuration = []): bool {
$pluginInstance = \Drupal::service('plugin.manager.condition')->createInstance($plugin_id);
$pluginInstance->setConfiguration($configuration);
$contextRepository = \Drupal::service('context.repository');
$availableContexts = $contextRepository->getAvailableContexts();
// Ensure that the contexts have data by getting corresponding runtime contexts.
$availableRuntimeContexts = $contextRepository->getRuntimeContexts(array_keys($availableContexts));
$pluginContextDefinitions = $pluginInstance->getContextDefinitions();
foreach ($pluginContextDefinitions as $name => $pluginContextDefinition) {
// Identify and fetch the matching runtime context, with the plugin's context definition.
$matches = \Drupal::service('context.handler')->getMatchingContexts($availableRuntimeContexts, $pluginContextDefinition);
$matchingContext = reset($matches);
// Set the value to the plugin's context, from runtime context value.
$pluginInstance->setContextValue($name, $matchingContext->getContextValue());
}
return $pluginInstance->evaluate();
}
/**
* Emits a breakpoint to the debug client.
*

Loading…
Cancel
Save