typo3fluidview-helperstypo3-9.x

How to compare a string with a variable in TYPO3 Fluid


I would like to do a simple comparisons, such as the equivalent of:

if ($somevar === 'somestring')

Now, I have found some examples where this is done like this:

<f:if condition="{somevar} == 'somestring'"> 
...

There are a number of places in the TYPO3 core 9.5 as well, example.

But the official documentation tells us otherwise and that we must use a weird workaround based on arrays:

Strings at XX/YY are NOT allowed, however, for the time being, a string comparison can be achieved with comparing arrays

If ViewHelper

Comparisons with strings, like ...., are not possible with Fluid yet because of the complex implementation.

(Extbase / Fluid)

Whatever that means ...

In order to avoid asking why: What is the recommended way to do comparisons of strings and variables in TYPO3 9 and since when is this possible?


Solution

  • As of TYPO3 8.7, the Fluid if-ViewHelper can do string, numeric and array comparisons without the workaround of putting strings into arrays. However, there's no support for globbing or regular expressions (the sky is the limit if you write a custom ViewHelper in PHP).

    Supported comparison operators are: ==, !=, <, <=, >, >= and %. There's also support for logical operators && and ||. You can negate a boolean with ! (like !{enable}).

    I've heard that the documentation team is hard at work updating and reorganizing the Fluid documentation. In the meantime, this page has many useful tips & tricks: https://usetypo3.com/24-fluid-tips.html

    Examples (using a mix of tag and inline syntax):

    1. String comparison: compare variable with string
    <f:variable name="foo">stuff</f:variable>
    <f:if condition="{foo} == 'stuff'">
        <f:render partial="FooPartial" arguments="{foo: foo}" />
    </f:if>
    
    1. Comparing integers (Fluid inline syntax)
    {f:variable(name: 'bar', value: 123)}
    {f:variable(name: 'baz', value: 50)}
    {f:if(condition: '{bar} > {baz}', then: 'This will print')}
    
    1. Boolean operators: &&, ||
    <f:if condition="{bar} > {baz} && {baz} < 100">This will print.</f:if>
    
    1. The string "false" will evaluate to boolean false (Fluid inline syntax)
    {f:variable(name: 'untrue', value: 'false')}
    {f:if(condition: untrue, then: 'Will not print', else: 'Will print')}