Skip to content

Instantly share code, notes, and snippets.

@DieterHolvoet
Created May 19, 2023 21:52
Show Gist options
  • Save DieterHolvoet/1804206bde05a3a2bed93925a5fc2071 to your computer and use it in GitHub Desktop.
Save DieterHolvoet/1804206bde05a3a2bed93925a5fc2071 to your computer and use it in GitHub Desktop.
Render a Plausible embed in a Drupal admin
<?php
namespace Drupal\yourmodule\Controller;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\Core\Theme\ThemeManagerInterface;
use Drupal\gin\GinSettings;
class StatisticsController
{
public function __construct(
protected ThemeHandlerInterface $themeHandler,
protected ThemeManagerInterface $themeManager,
) {
}
public function show(): array
{
$url = 'https://plausible.io/share/your-domain.com';
$params = [];
$params['auth'] = 'xxxxxxxxxxxxxxxxxxxxx';
$params['background'] = 'transparent';
$params['theme'] = 'auto';
$activeTheme = $this->themeManager->getActiveTheme();
if ($activeTheme->getName() === 'gin' || isset($activeTheme->getBaseThemeExtensions()['gin'])) {
$ginSettingsPathParts = [
DRUPAL_ROOT,
$this->themeHandler->getTheme('gin')->getPath(),
'src/GinSettings.php',
];
require_once implode(DIRECTORY_SEPARATOR, $ginSettingsPathParts);
$ginSettings = \Drupal::classResolver(GinSettings::class);
$params['theme'] = $ginSettings->get('enable_darkmode') ? 'dark' : 'light';
}
return [
'iframe' => [
'#type' => 'html_tag',
'#tag' => 'iframe',
'#attributes' => [
'plausible-embed' => true,
'src' => sprintf('%s?%s', $url, http_build_query($params)),
'scrolling' => 'no',
'frameborder' => '0',
'loading' => 'lazy',
'style' => 'width: 1px; min-width: 100%; height: 1600px;',
],
],
'script' => [
'#type' => 'html_tag',
'#tag' => 'script',
'#attributes' => [
'async' => true,
'src' => 'https://plausible.io/js/embed.host.js',
],
],
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment