Create a component

To understand what are components, read this section.

Configuration

In your config/packages/numbernine.yaml file, configure the path where to store components. By default it's src/Component/, if this path suits you then skip this step.

numbernine:
    components_path: 'src/My/Path/To/Components/'
1
2

Using CLI

Run this command in your terminal:

docker compose exec php bin/console numbernine:make:component
1

You'll be asked for a component name, enter the name you want. You can create subfolders, for example Post/PostAuthor.

File structure

A new folder is created with two files:

  • MyComponent/MyComponent.php

    This is the controller of the component template.

  • MyComponent/template.html.php

    This is the template.

Render a component from Twig

To render the component, use this Twig function:

{{ N9_component('MyComponent') }}
1

Inject variables in a component

You can inject some variables from the parent template into your component:

{{ N9_component('MyComponent', {example: 'string variable'}) }}
1

To catch it, your component need to implement the corresponding setter:

final class MyComponent implements ComponentInterface
{
    private string $example;

    public function setExample(string $example): void
    {
        $this->example = $example;
    }

    // ...
}
1
2
3
4
5
6
7
8
9
10
11

Expose variables to the component's template

Every component must implement getTemplateParameters() which returns an array of exposed variables to the template.

final class MyComponent implements ComponentInterface
{
    // ...

    public function getTemplateParameters(): array
    {
        return [
            'example' => $this->example,
        ];
    }
}
1
2
3
4
5
6
7
8
9
10
11

The Twig template can now use this variable:

<p>Displaying custom variable: {{ example }}.</p>
1

Injecting a service in your component

Every component is a service. This means you can use dependency injection like with any other service.

final class MyComponent implements ComponentInterface
{
    public function __construct(
        EventDispatcherInterface $eventDispatcher
    ) {
        // ...
    }
}
1
2
3
4
5
6
7
8