PHP code example of kenny1911 / twig-view

1. Go to this page and download the library: Download kenny1911/twig-view 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/ */

    

kenny1911 / twig-view example snippets




use Kenny1911\TwigView\Attribute\View;

#[View(template: 'hello.html.twig')]
final class HelloView
{
    public function __construct(
        public readonly string $name,
    ) {}
}



use Kenny1911\TwigView\View;

/**
 * @implements View<array{
 *     name: string
 * }>
 */
final class HelloView implements View
{
    public function __construct(
        private readonly string $name,
    ) {}

    #[\Override]
    public function template(): string
    {
        return 'hello.html.twig';
    }

    #[\Override]
    public function context(): array
    {
        return ['name' => $this->name];
    }
}

$viewRenderer->render(new HelloView('World'));
// Result: "<p>Hello World</p>"



use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;

final class HelloController
{
    #[Route('/hello/{name}', name: 'hello')]
    public function hello(string $name): HelloView
    {
        return new HelloView($name);
    }
}



use Kenny1911\TwigView\Test\ViewTest;
use Kenny1911\TwigView\ViewRenderer;
use PHPUnit\Framework\TestCase;
use Twig\Environment;
use Twig\Loader\ArrayLoader;

final class HelloViewTest extends TestCase
{
    use ViewTest;

    #[\Override]
    protected function createViewRenderer(): \Kenny1911\TwigView\ViewRenderer
    {
        return new ViewRenderer(
            new Environment(
                new ArrayLoader([
                    'hello.html.twig' => 'Hello {{ name }}',
                ]),
                [
                    'strict_variables' => true,
                ],
            ),
        );
    }

    #[\Override]
    protected function iterateViews(): iterable
    {
        yield new HelloView('World');
        // Add all test cases for your views here
    }
}



abstract class ViewTestCase extends KernelTestCase
{
    use ViewTest;
    
    #[\Override]
    protected function createViewRenderer(): \Kenny1911\TwigView\ViewRenderer
    {
        self::bootKernel();
        
        return self::getContainer()->get('twig.view_renderer');
    }
}

final class HelloViewTest extends ViewTestCase
{
    #[\Override]
    protected function iterateViews(): iterable
    {
        yield new HelloView('World');
        // Add all test cases for your views here
    }
}