twig_state_access
11 sites
Security covered
Twig State Access module provides new twig extensions to access Drupal state/private tmp state APIs in readonly mode.
Features
Typically in Drupal to pass Drupal state values to twig templates you usually use preprocess hooks to retrieve the value via Drupal state service and then inject it in template variables array, this module gives you access to retrieve any state value directly from the twig file using new twig extensions.
Examples:
Before enabling Twig state access module:
my_module.module file :
/**
* Implements hook_preprocess_hook().
*/
function my_module_preprocess_page(&$variables) {
...
$toto = Drupal::state()->get('toto', 'Default toto value here');
$all_bars = Drupal::state()->getMultiple(['bar1', 'bar2', 'bar3']);
$foo = Drupal::service('tempstore.private')->get('my_module')->get('foo');
$foo_metadata = Drupal::service('tempstore.private')->get('my_module')->getMetadata('foo');
$variables['toto'] = $toto;
$variables['all_bars'] = $all_bars;
$variables['foo'] = $foo;
$variables['foo_metadata'] = $foo_metadata;
...
}
page.html.twig file :
...
<div>
<ul>
<li>Toto: {{ toto }}</li>
<li>All bars: {{ all_bars|join(', ') }}</li>
<li>Foo: {{ foo }}</li>
<li>Foo Metadata: {{ foo_metadata.updated }} - {{ foo_metadata.ownerId }}</li>
</ul>
</div>
...
After enabling twig state access module:
my_module.module file :
/**
* Implements hook_preprocess_hook().
*/
function my_module_preprocess_page(&$variables) {
...
// No more state API code here.
...
}
page.html.twig file :
...
<div>
// First param is the key to retrieve, second optional param is the default value.
{% set toto = drupal_state('toto', 'Default toto value here') %}
// To retrieve multiple keys at once, return an array of related values.
{% set all_bars = drupal_state(['bar1', 'bar2', 'bar3']) %}
// First param is the collection, second param is the key to retrieve.
{% set foo = drupal_private_state('my_module', 'foo') %}
// When third param is set to true then key related metadata is retrieved.
{% set foo_metadata = drupal_private_state('my_module', 'foo', true) %}
<ul>
<li>Toto: {{ toto }}</li>
<li>All bars: {{ all_bars|join(', ') }}</li>
<li>Foo: {{ foo }}</li>
<li>Foo Metadata: {{ foo_metadata.updated }} - {{ foo_metadata.ownerId }}</li>
</ul>
</div>
...
Additional Requirements
This module requires no modules outside of Drupal core.