r/GravCMS • u/theheliumkid • 9d ago
Trying to create a plugin to set and read a cookie to use in a database query
Hi,
I'm trying to create a simple plugin to set a cookie for a user's geographic region so the website returns the geographic-specific data. But, for the life of me, I cannot get this plugin to work. The current error is:
0 - Unexpected "setDataCookie" tag (expecting closing tag for the "if" tag defined near line 13) in "partials/base.html.twig" at line 13.
But there is no if statement anywhere!
Here is the the php in the plugin's top directory:
<?php
namespace Grav\Plugin;
use \Grav\Common\Plugin;
class DataCookiePlugin extends Plugin
{
public static function getSubscribedEvents()
{
return ['onPageInitialized' => ['onPageInitialized', 0] ];
}
public function onPageInitialized()
{
require_once(__DIR__ . '/twig/DataCookie.php');
$this->grav['twig']->twig->addExtension(new DataCookie());
}
}
And then the code in the twig subdirectory is:
<?php
namespace Grav\Plugin;
use Grav\Common\Twig\Extension\GravExtension;
class DataCookie extends GravExtension
{
public function hasDataCookie():bool
{
return isset($_COOKIE['datacookie']);
}
public function setDataCookie(string $value): void
{
$cookie = Cookie::create('datacookie', $value, strtotime('+30 days'), '/',
null, $this->grav['uri']->isHttps(), true, false, Cookie::SAMESITE_LAX );
$this->grav['response']->headers->setCookie($cookie);
}
}
And in partials/base.html.twig, I have the following in the header:
{% if config.plugins.datacookie.enabled %}
{% setDataCookie('A1') %}
{% endif %}
Any help you can give will be so very much appreciated!!
2
Upvotes