PHP code example of zenstruck / twig-service-bundle
1. Go to this page and download the library: Download zenstruck/twig-service-bundle library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
zenstruck / twig-service-bundle example snippets
// ...
use Zenstruck\Twig\AsTwigFunction;
class SomeService
{
// ...
#[AsTwigFunction] // will be available as "fn_someMethod()" in twig
public function someMethod($arg1, $arg2): string
{
// ...
}
#[AsTwigFunction('alias')] // will be available as "fn_alias()" in twig
public function anotherMethod($arg1, $arg2): string
{
// ...
}
}
use Zenstruck\Twig\AsTwigFunction;
#[AsTwigFunction] // will be available as "some_function" in twig
function some_function($arg1, $arg2): string
{
// ...
}
#[AsTwigFunction('alias')] // will be available as "alias" in twig
function another_function($arg1, $arg2): string
{
// ...
}
namespace App\Twig\Service;
// ...
use Zenstruck\Twig\AsTwigService;
#[AsTwigService(alias: 'posts')]
class PostService
{
public function __construct(private PostRepository $repo)
{
}
/**
* @return Post[]
*/
public function latestPosts(int $number = 10): array
{
return $this->repo->findLatestPosts($number);
}
}
namespace App\Twig\Service;
// ...
use Zenstruck\Twig\AsTwigService;
#[AsTwigService(alias: 'image_transformer')]
class ImageTransformer
{
public function __invoke(string $imageUrl, string ...$transformations): string
{
// adds transformation to url and returns new url
}
}
twig
{# as a function: #}
{{ fn('some_function', 'foo', 'bar') }}
{{ fn('alias', 'foo', 'bar') }}
{# as a filter: #}
{{ 'foo'|fn('some_function', 'bar') }}
{{ 'foo'|fn('alias', 'bar') }}
twig
{# as a function: #}
{{ fn_some_function('foo', 'bar') }}
{{ fn_alias('foo', 'bar') }}
{# as a filter: #}
{{ 'foo'|fn_some_function('bar') }}
{{ 'foo'|fn_alias('bar') }}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.