Skip to content

[RFC] Twig |serialize Filter for the Serializer #40227

Closed
@weaverryan

Description

@weaverryan

Description
Hi!

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.

Example

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() {
        ReactDOM.render(
            <ProductComponent product={this.productValue} />,
            this.element
        )
    }
}

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.

Cheers!

Metadata

Metadata

Assignees

No one assigned

    Labels

    RFCRFC = Request For Comments (proposals about features that you want to be discussed)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions