Skip to content

Commit 8ee27e3

Browse files
committed
Add Twig extension
1 parent e73af5b commit 8ee27e3

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
66

77
## [Unreleased]
88

9+
## [0.6.0] - 2020-07-23
10+
### Added
11+
- Add Twig extension
12+
913
## [0.5.0] - 2020-07-23
1014
### Removed
1115
- Remove hook_event_dispatcher dependency
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?php
2+
3+
namespace Drupal\wmsettings\Twig\Extension;
4+
5+
use Drupal\Core\Cache\CacheableMetadata;
6+
use Drupal\Core\Entity\EntityInterface;
7+
use Drupal\Core\Render\RendererInterface;
8+
use Drupal\wmsettings\Service\WmSettings;
9+
use Twig\Extension\AbstractExtension;
10+
use Twig\TwigFunction;
11+
12+
class SettingExtension extends AbstractExtension
13+
{
14+
/** @var RendererInterface */
15+
protected $renderer;
16+
/** @var WmSettings */
17+
protected $wmSettings;
18+
19+
public function __construct(
20+
RendererInterface $renderer,
21+
WmSettings $wmSettings
22+
) {
23+
$this->renderer = $renderer;
24+
$this->wmSettings = $wmSettings;
25+
}
26+
27+
public function getFunctions(): array
28+
{
29+
return [
30+
new TwigFunction('setting', [$this, 'getSetting']),
31+
];
32+
}
33+
34+
public function getSetting($bundle)
35+
{
36+
$entity = $this->wmSettings->read($bundle);
37+
38+
// Workaround to include caching metadata of the settings entity
39+
if ($entity instanceof EntityInterface) {
40+
$build = [];
41+
CacheableMetadata::createFromObject($entity)
42+
->applyTo($build);
43+
$this->renderer->render($build);
44+
}
45+
46+
return $entity;
47+
}
48+
}

wmsettings.services.yml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,10 @@ services:
2020
class: Drupal\wmsettings\EventSubscriber\SettingsSubscriber
2121
arguments:
2222
- '@cache_tags.invalidator'
23+
24+
wmsettings.twig_extension:
25+
class: Drupal\wmsettings\Twig\Extension\SettingExtension
26+
tags: ['twig.extension']
27+
arguments:
28+
- '@renderer'
29+
- '@wmsettings.settings'

0 commit comments

Comments
 (0)