Using CookieConsent to render conditional HTML in a Twig template #645
fabian-st
started this conversation in
Show and tell
Replies: 1 comment
-
|
Updated to allow checking for category and single service consent: <?php
namespace App\Twig;
use Symfony\Component\HttpFoundation\RequestStack;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
define('CC_COOKIE', 'cc_cookie');
class ConsentExtension extends AbstractExtension
{
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public function getFunctions(): array
{
return [
new TwigFunction('category_consent_exists', [$this, 'categoryConsentExists']),
new TwigFunction('service_consent_exists', [$this, 'serviceConsentExists']),
];
}
public function categoryConsentExists($category): bool
{
$request = $this->requestStack->getCurrentRequest();
$ccRaw = $request->cookies->get(CC_COOKIE);
if ($ccRaw === null) {
return false;
}
$ccCategories = json_decode($ccRaw)->categories;
return in_array($category, $ccCategories);
}
public function serviceConsentExists($service, $category): bool
{
$request = $this->requestStack->getCurrentRequest();
$ccRaw = $request->cookies->get(CC_COOKIE);
if ($ccRaw === null) {
return false;
}
$ccServices = json_decode($ccRaw)->services;
if (!property_exists($ccServices, $category)) {
return false;
}
return in_array($service, $ccServices->$category);
}
}{% if service_consent_exists('matomo', 'analytics') %}
<!-- Your HTML goes here -->
{% endif %} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I created this very simple extension for Symfony Twig, which allows you to check if a user has given their consent for a specific category:
To use the extension, place it under
src/App/Twig/ConsentExtension.phpand include it in your services.yaml:Afterwards, use it in your Twig templates as follows:
{% if consent_exists('tracking') %} <!-- Your HTML goes here --> {% endif %}Beta Was this translation helpful? Give feedback.
All reactions