Symfony 6 Certification New exam with updated questions 100% online Show your expertise

New in Symfony 5.3: Twig Serialize Filter

Symfony 5.3 is backed by JoliCode. JoliCode is a team of passionate developers and open-source lovers, with a strong expertise in PHP & Symfony technologies. They can help you build your projects using state-of-the-art practices.

Contributed by
Jesse Rushlow
in #40323.

In Symfony applications there are several methods of passing data from the backend to the frontend. Some applications make Ajax requests whenever they need data and others prefer to pass it in Twig templates as HTML attributes or JavaScript variable values.

In Symfony 5.3 we’ve added a simpler way of doing this: the new serialize Twig filter. This filter accepts any data that can be serialized by the Serializer component and returns a serialized string in the specified format.

In the following example, the Twig template uses the stimulus_controller() function from the Symfony Stimulus Bridge. If the template is passed a variable called product, you can now serialize its contents to use it in the Stimulus function call:

{{ stimulus_controller('product-show', {
    product: product|serialize('json', { groups: 'product:read'})
}) }}

This would render something like this:

<div data-controller="product-show"
Help the Symfony project!

As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.


This is great! Thank you
&quot;, &quot;, &quot; ... that is very ineffective. If you replace html attribute quotes with apostrophes, then there is no need for escaping the quotes: ...
... < div data-something='{"foo":"bar"}' ... >

(why it removes tags instead of escaping them?)
That's nice! Thanks

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.