How to assign variable in fluid?

23.7k views Asked by At

I want viewhelper that can be helpful to assign variable in fluid, I dont want variable to be passed from controller.

3

There are 3 answers

0
Mihir Bhatt On BEST ANSWER

Install extension called vhs from TYPO3 repository

Define namespace like following at the top of your fluid template

{namespace v=FluidTYPO3\Vhs\ViewHelpers}

Then use set viewhelper

<v:variable.set name="test" value="12345" />
Value of test : {test}

{test} will return value 12345

For registering global variable

<v:variable.register.set name="test" value="12345"/>]

Get value of global variable

Value of global variable : <v:variable.register.get name="test">

Since TYPO3 8.7, fluid introduces viewhelper for the variable (No need of VHS)

<f:variable name="myvariable">My variable's content</f:variable>
<f:variable name="myvariable" value="My variable's content"/>

With inline style usage

{f:variable(name: 'myvariable', value: 'My variable\'s content')}
{myoriginalvariable -> f:variable.set(name: 'mynewvariable')}
0
Bernd Wilke πφ On

Since first fluid version it is possible to define variables for a special area: there is the VH f:alias which enables you to define new variables in the range of this VH. And that is the difference to the variable.set VH from ext:vhs.

<f:alias map="{firstName: 'John', lastName: 'Doe'}">
     <p>Hello, my name is {firstName} {lastName}</p>
</f:alias> 

<f:for each="{users}" as="user" iteration="iterator">
    <f:if condition="{iterator.isFirst}">
        <v:variable.set name="firstName">{user.firstName}</v:variable.set>
        <v:variable.set name="lastName">{user.lastName}</v:variable.set>
    </f:if>
    :
    do other output
    :
</f:for>
<p>the first user was {firstName} {lastName}.</p>  

The problem with setting variables inside the fluid is the possibility to do programming logic inside fluid:

<v:variable.set name="counter" value="0">
<f:for each="records" as="record">
   <f:if condition="{record.flag}">
       <v:variable.set name="counter">
           <f:cObject typoscriptObjectPath="lib.calc">
              {counter}+1
           </f:cObject>
       </v:variable.set>
   </f:if>
</f:for>
<p>there are {counter} records with a flag set.</p>

with this typoscript

lib.calc = TEXT
lib.calc.current = 1
lib.calc.prioriCalc = 1
0
Sven On

Since TYPO3 8.6, this is possible without extension "vhs":

<f:variable name="myvariable" value="My variable's content"/>

See https://docs.typo3.org/typo3cms/extensions/core/Changelog/8.6/Feature-79402-VariableViewHelperForFluid.html