Submitted by
Dmitro
on
Create file custom_base\src\TwigExtension\ActiveThemeUrlExtension.php:
<?php
namespace Drupal\custom_base\TwigExtension;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* Provides a Twig extension to retrieve the active theme absolute url.
*/
class ActiveThemeUrlExtension extends AbstractExtension {
/**
* Theme Handler service.
*
* @var \Drupal\Core\Extension\ThemeHandlerInterface
*/
protected $themeHandler;
/**
* The config factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* Constructs a new ActiveThemeUrlExtension object.
*
* @param \Drupal\Core\Extension\ThemeHandlerInterface $themeHandler
* The theme handler.
* @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
* The config factory.
*/
public function __construct(
ThemeHandlerInterface $themeHandler,
ConfigFactoryInterface $configFactory
) {
$this->themeHandler = $themeHandler;
$this->configFactory = $configFactory;
}
/**
* {@inheritdoc}
*/
public function getFunctions(): array {
return [
new TwigFunction('absolute_theme_url', [
$this,
'getActiveThemeAbsoluteUrl',
]),
];
}
/**
* Retrieves the active theme absolute url.
*
* @return string
* The absolute url to the active theme.
*/
public function getActiveThemeAbsoluteUrl(): string {
global $base_url;
$config = $this->configFactory->get('system.theme');
$defaultThemeName = $config->get('default');
$theme = $this->themeHandler->getTheme($defaultThemeName);
$theme_path = $theme->getPath();
return $base_url . '/' . $theme_path;
}
}
Add to custom_base.services.yml:
af2_base.twig_extension:
class: Drupal\af2_base\TwigExtension\ActiveThemeUrlExtension
arguments: ['@theme_handler', '@config.factory']
tags:
- { name: twig.extension }
Now in twig templates available {{ absolute_theme_url() }}