How to assign complex objects to JavaScript variables with Typo3's Fluid

Objective: assign a complex object, Array or Object, to a JavaScript variable in a Fluid template of Typo3.

We will have to "insert" a structured value in a JavaScript variable, included into a Fluid template: Array or Object, In Fluid, codes are often quite illegible with tags of the type
<! [CDATA [...] ]>
<f: format.raw>{string}</ f: format.raw>
<f: format.cdata>{string}</ f: format.cdata>

These solutions, in addition to being impractical, do not have the ability to assign complex and structured values, but only simple variables and, at most, a simple array to which, then, apply split functions to obtain an usable array.

Yes, because Fluid generates only strings from objects assigned via Controller.

The most practical solution, which avoids the use of "fragmentation" of the JavaScript code with the Fluid tags, is to include, in the Fluid template, an "input" element with type "hidden", and assign the complex variable, Array or Object, to "data" attribute.

Let's start from the beginning.

In the Controller, I assign the Object to the view

$view->assign('numberingJson', json_encode($numbering));

where $numbering is an associative Array. Note that the Array is serialized in JSON format to get a string.

The next step is to insert a "hidden" input tag in the Fluid template and assign the "numberingJson" Fluid variable to the "data" attribute

<f: form.hidden id="numbering" data="{numbering: '{numberingJson}'}" />

Finally, by JavaScript, retrieve the value in "data('numbering')" and perform the needed operations

const numbering = $('#numbering').data('numbering');

That's all, simple and clean.

Comments

No comments