Skip to main content

Trying out Symfony Twig Components

Last summer, I attended SymfonyWorld Online 2021 Summer Edition, and I was fascinated by Ryan Weavers talk about Symfony Twig Components.

As the README says on the github project page

Twig components give you the power to bind an object to a template, making it easier to render and re-use small template "units" - like an "alert", markup for a modal, or a category sidebar.

I found the presentation very promising, and I wanted to try using twig components in combination with stimulus for the frontend of dikdikdik, a hobby webapp I maintain, to keep track of the score for the wiezen card game.

Now we're a couple of months later, and I finally found time to write my first component. I followed the instructions in the README, but what I got was a server error: Unknwon "component" function.

Unknown "component" function

I first tried to fix this to define the ComponentExtension class as service in serices.yaml. I got more error messages, and I kept on adding all kind of dependendent services. Obviously this failed at some point.

So I spent an evening on messing around with configuration files, reading documentation and sample code, and finally I found out what was wrong: the twig component bundle was not added to config/bundles.php. I just had to add this line:

    Symfony\UX\TwigComponent\TwigComponentBundle::class => ['all' => true],

(See also commit c0080e43 in the dikdikdik git repository.)

Now I thought adding such a line should have been done automatically by flex, when installing the symfony/ux-twig-component package. So maybe something is wrong with the flex recipe. But I'm not sure where to find that recipe. When I run

composer recipes symfony/ux-twig-component

I get an error as well:

  [ErrorException]                                     
  Trying to access array offset on value of type null 

This might be related.

Anyway, I am not sure if the issue I had is caused by a bug in symfony-ux-twig-component, or maybe there's just something wrong with the setup of my Symfony project. But here you are, if you also happen to run into this problem, now there's a solution that can be found by Google and alike 🙂. If you have a better insight in what went wrong here, please let me know.

I'll keep you posted on using the twig components for my frontend. But keep in mind that I have limited free time to work on this hobby project.

Update: I created my first Symfony Live Component!

Comments

Comments powered by Disqus