Add custom twig extension with path functions
This commit is contained in:
parent
3a7870a68b
commit
0ef77b2aa7
40
src/Service/SnipParser/Twig/SnipTwigExtension.php
Normal file
40
src/Service/SnipParser/Twig/SnipTwigExtension.php
Normal file
@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Service\SnipParser\Twig;
|
||||
|
||||
use App\Repository\SnipRepository;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
use Symfony\Component\Routing\RouterInterface;
|
||||
use Twig\Extension\AbstractExtension;
|
||||
use Twig\TwigFunction;
|
||||
|
||||
class SnipTwigExtension extends AbstractExtension
|
||||
{
|
||||
public function __construct(
|
||||
#[Autowire(lazy: true)] private readonly RouterInterface $router,
|
||||
#[Autowire(lazy: true)] private readonly SnipRepository $snipRepo,
|
||||
) {}
|
||||
|
||||
public function getFunctions(): array
|
||||
{
|
||||
return [
|
||||
new TwigFunction('snipPath', $this->snipPath(...)),
|
||||
new TwigFunction('snipLink', $this->snipLink(...), [
|
||||
'is_safe' => ['html'],
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
function snipPath(int $id): string
|
||||
{
|
||||
return $this->router->generate('snip_single', [
|
||||
'snip' => $id,
|
||||
]);
|
||||
}
|
||||
|
||||
function snipLink(int $id): string
|
||||
{
|
||||
$snip = $this->snipRepo->find($id);
|
||||
return sprintf('<a class="btn btn-sm btn-primary" href="%s">%s</a>', $this->snipPath($id), $snip);
|
||||
}
|
||||
}
|
@ -11,6 +11,7 @@ class TwigParser extends AbstractParser
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SnipLoader $snipLoader,
|
||||
private readonly SnipTwigExtension $snipTwigExtension,
|
||||
) {}
|
||||
|
||||
public function safeParseView(string $content): string
|
||||
@ -22,6 +23,7 @@ class TwigParser extends AbstractParser
|
||||
$this->snipLoader,
|
||||
]);
|
||||
$twig = new Environment($loader);
|
||||
$twig->addExtension($this->snipTwigExtension);
|
||||
|
||||
return $twig->render('index');
|
||||
}
|
||||
|
@ -1,6 +1,6 @@
|
||||
<nav class="navbar navbar-expand-md navbar-dark bg-dark" style="z-index: 1;">
|
||||
<div class="container-fluid">
|
||||
<a title="BlueLinked Eco System" class="navbar-brand" href="{{ path('home') }}">SNIPS</a>
|
||||
<a title="Snips" class="navbar-brand" href="{{ path('home') }}">SNIPS</a>
|
||||
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbar"
|
||||
aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
|
Loading…
x
Reference in New Issue
Block a user