[RFC] Twig |serialize Filter for the Serializer


I often create a object|serialize('json') style Twig filter in my projects/tutorials so that I can pass data directly into JavaScript instead of needing to make an AJAX call.


Here’s an example using Stimulus (& React, but this applies to just Stimulus or just React):

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

<!-- this renders -->
<div data-controller="product-show" data-product-show-product-value="{&quot;id&quot;:5,...}"><div>

The controller might then look like this:

import { Controller } from 'stimulus';
import ReactDOM from 'react-dom';
import React from 'react';
import ProductComponent from '../components/ProductComponent';

export default class extends Controller {
    static values = {
        product: Object

    connect() {
            <ProductComponent product={this.productValue} />,

In this example, I’ve successfully passed a product object as JSON through Stimulus and into React (though, again, none of this is specific to React or Stimulus). This allows my React component to not need to make an AJAX call on load to get this data.


1 possible answer(s) on “[RFC] Twig |serialize Filter for the Serializer

  1. Big +1 for me. The only concern I may have would be exposing sensitive data publicly, but I guess that’s the responsibility of the user and they would expose them in an API anyway.