Diving Into TYPO3 Fluid [50+ Tips]

Diving Into TYPO3 Fluid [50+ Tips]

TYPO3 Fluid - One of the unique frontend template engine of TYPO3 CMS! As a TYPO3 integrator or developer, you should have mastery of the TYPO3 Fluid template engine. In this blog, I want to share helpful tips & tricks of TYPO3 Fluid. Get ready!

Fluid is a powerful Open Source template engine system used in TYPO3, Neos CMS, and Flow PHP Framework. If you are a beginner, I highly recommend you read one of my popular blogs, How to Use TYPO3 Fluid? (Basic to Advanced Guide). In this blog, you will find TYPO3 Fluid hints from my personal experience and includes valuable 24 Tips of TYPO3 Fluid by Claus Due (Developer and Maintainer of TYPO3 Fluid).

My dear TYPO3 reader, As you know, my ritual ;) It’s time to say thanks to the TYPO3 people who contributed to the TYPO3 Fluid Open Source project. We appreciate your dedication and work on TYPO3 Fluid. Huge thanks to Claus Due, Let’s give big hands! #T3Kudos!

Tips & Tricks of TYPO3 Fluid

What/Why/How TYPO3 Fluid?

“TYPO3 Fluid - A fast, secure and extensible template engine for PHP.” - typo3.org

TYPO3 fluid is mainly used by the Front-end developers who integrate HTML/CSS/JavaScript to output at the website. While incorporating your templates in TYPO3, you don’t require knowledge of PHP scripting language - Just use innovative TYPO3 Fluid ;) Read more

Responsive Image Rendering in TYPO3 Fluid

Many people still use old-style image rendering in TYPO3 fluid, e.g., a custom picture tag with extra javascript for responsive image rendering. From TYPO3 v10, we have full-responsive design support within the TYPO3 core. You should consider rendering your response image with the TYPO3 fluid code snippet.

 

<f:media
    class="your-css-class"
    file="{fileObject}"
    width="{imageWidth}"
    height="{imageHeight}"
    alt="{imagAlt}"
    title="{imageTitle}"
    loading="{settings.media.lazyLoading}"
    additionalAttributes="{srcset: '{f:uri.image(image: file, maxWidth: 768)} 768w,
                                    {f:uri.image(image: file, maxWidth: 990)} 990w,
                                    {f:uri.image(image: file, maxWidth: 1200)} 1200w,
                                    {f:uri.image(image: file, maxWidth: 1440)} 1440w,
                                    {f:uri.image(image: file, maxWidth: 1900)} 1900w',
                           sizes: '(min-width: 1200px) 50vw, 100vw'}”
/>

How to Disable the Cache of TYPO3 Fluid?

Hmm, so you want to write some TYPO3 Fluid code that should be bypassed from the TYPO3 fluid cache. You can use the TYPO3 Fluid viewhelper call <f:cache.disable />.

 

<f:cache.disable>
   Write down your TYPO3 fluid code, which will consistently execute without the TYPO3 cache.
</f:cache.disable>

How to Create TYPO3 Fluid Variables?

To create a variable, assign value and use it at your section or particular is helpful to write better TYPO3 fluid code. As a TYPO3 beginner, you may not know how to create TYPO3 fluid variables in many ways, as below.

 

<!-- Using TYPO3 Fluid ViewHelper -->
<f:variable name="fluidVar" value="Your Static Value"/>
<f:variable name="fluidVar">Assign Large Expression</f:variable>

<!-- Using TYPO3 Fluid Inline Notation -->
{f:variable(name: 'fluidVar', value: 'Your Static Value')}
{my:expensiveViewHelper() -> f:variable(name: 'fluidVar')}

How to Use Variables in TYPO3 Fluid?

Now it’s time to use our very own created variables in TYPO3 fluid. You can use it anywhere to render variables, pass to partial, verify with if conditions, etc. Here are a few snippets.

 

<!-- Create TYPO3 Fluid Variable -->
<f:variable name="fluidVar" value="Your Static Value"/>

<!-- Simply Print TYPO3 Fluid Variabe -->
<div class=”myClass”>{fluidVar}</div>

 

<!-- Pass as argument into TYPO3 Fluid f.render -->
<f:render partial="MyPartial" arguments="{fluidVar: fluidVar}"/>

{var1{var2}} Get Dynamic Variables in Fluid

You may be required to call values with a dynamic variable in some situations - I know it’s hard to understand what a dynamic variable is? But let’s have a look at a few TYPO3 fluid code examples to understand it well.

 

<!-- Example 1. Create Variable with Two-dimensional Array. And, let’s call the value of index-1 from fluidVar variable (using another variable call index) →

<f:variable name="fluidVar" value="{0: 'foo', 1: 'bar'}" />
<f:variable name="index" value="1" />

{fluidVar.{index}}
<!-- Output: bar -->

<!-- Example 2 -->
<f:variable name="fluidVarOne" value="Value of Variable 1" />
<f:variable name="fluidVarTwo" value="Value of Variable 2" />
<f:variable name="chooseType" value="Two" />

{fluidVar{chooseType}}
<!-- Output: Value of Variable 2 -->

Declares New Variable from Other Variable

In rare cases, you will need to alias from one variable to another. You can use <f:alias /> TYPO3 fluid viewhelper.

 

<f:alias map="{x: 'foo'}">{x}</f:alias>
<f:alias map="{x: foo.bar.baz, y: foo.bar.baz.name}">
  {x.name} or {y}
</f:alias>

 

How to Add CSS/JavaScript In TYPO3 Fluid Template?

From TYPO3 v9, TYPO3 core provides a feature to add your JavaScript/CSS assets within your TYPO3 fluid template. Here is the snippet code.

 

<f:section name="HeaderAssets">
    <link rel="stylesheet" href="{f:uri.resource(path: 'Css/styles.css')}"/>
    <script type="text/javascript src="{f:uri.resource(path: 'JavaScript/script.js')}"></script>
</f:section>

 

<f:section name="FooterAssets">
    <link rel="stylesheet" href="{f:uri.resource(path: 'Css/styles.css')}"/>
    <script type="text/javascript src="{f:uri.resource(path: 'JavaScript/script.js')}"></script>
</f:section>

How Get Data of Current Page in TYPO3 Fluid?

It’s effortless; TYPO3 provides the default {data} variable, which includes all the properties of the currently rendered page.

 

<f:debug>{data}</f:debug>

What is {_all} in TYPO3 Fluid?

Namely, it includes all the variables created within the template, layout, section, or partial. Whenever you develop your template, section, or partial, keep on your debugger to see available variables within your scope.

 

<f:debug>{_all}</f:debug>
<f:debug title="My Title" maxDepth="5"
    blacklistedClassNames="{0:'Tx_BlogExample_Domain_Model_Administrator'}"
    blacklistedPropertyNames="{0:'posts'}"
    plainText="true" ansiColors="false"
    inline="true"
    >
        {blogs}
</f:debug>

5 Ways to Import Namespaces in TYPO3 Fluid

If you are developing customer TYPO3 Fluid ViewHelpers, then it’s a bit interesting to know, How can you import Namespaces for your registered Namespaces how you can

 

<!-- 1. Default Preserved for XSD -->
<html xmlns:f="typo3.org/ns/TYPO3/CMS/F…">
Your TYPO3 Fluid Code
</html>

<!-- 2. Default + Allow Namespaces of TYPO3 Fluid -->
<html xmlns:f="typo3.org/ns/TYPO3/CMS/F…" data-namespace-typo3-fluid="true">
Your TYPO3 Fluid Code
</html>

<!-- 3.  Register Single Namespace -->
{namespace foo=MyVendor\MyPackage\ViewHelpers}
Your TYPO3 Fluid Code

<!-- 4. Import Single Namespace -->
{namespace foo}
Your TYPO3 Fluid Code

<!-- 5. Import Multiple Namespace -->
{namespace fo*}
Your TYPO3 Fluid Code

Declare and Use Multiple Namespaces

That’s quite simple; you can register and use multiple namespaces.

 

{namespace f=Vendor\MyFluidOverrides\ViewHelpers}
{namespace my=Vendor\MyExtensionOne\ViewHelpers}

All-in-One to Know About Fluid’s Inline Notation

Inline notation is very interesting; you should have in-depth knowledge and understanding of TYPO3 fluid’s inline notation. Let’s try to understand by asking questions and examples.

What/How is Fluid’s Inline Notation for ViewHelpers

Let’s consider f:count ViewHelper. You can f:count in three ways which work the same.

 

<f:count>{sliderElements}</f:count>
{f:count(subject: sliderElements)}
{sliderElements -> f:count()}

 

When should I use Inline Notation at all?

In general cases, notation syntax is helpful while checking and rendering inline within a fluid or html tag. Mostly it will be helpful for you to use at conditions eg., <f:if> condition.

 

<f:if condition="<f:count>{sliderElements}</f:count> > 1">
    <!-- slider html code here -->
</f:if>
<f:if condition="{sliderElements -> count()} > 1">

 

Okay, But why and when do I want to nest them?

Consider the below example where you want to configure currency format using <f:format.currency /> viewhelper. You can see how easy to configure <f:translate /> ViewHelper with efficient use as inline notation.

 

{cheapestPrice -> f:format.currency(
    thousandsSeparator: '{f:translate(key:\'sepThousands\')}',
    decimalSeparator: '{f:translate(key:\'sepDecimals\')}',
    decimals: 2
)}

 

Hmm, Interesting! What About Escaping Level?

Well, it’s unlimited but make sure to consider it as a practical and readable solution as it’s all about saving time and energy to understand and develop TYPO3 fluid code using inline notation.

 

1st level: 0 '
2nd level: 1 \'
3rd level: 3 \\\'
4th level: 7 \\\\\\\'

<f:translate
  key="logForNonPageRelatedActionsOrRootLevelOrPage"
  arguments="{
    0: '{f:translate(
      key:\'forPage\',
      htmlEscape:\'0\',
      arguments:\'{
        0:\\\'{belog:be.pagePath(pid:\\\\\\\'{pid}\\\\\\\')}\\\',
        1:\\\'{pid}\\\'
      }\'
    )}',
    1: '{f:format.date(format:\'{settings.dateFormat} H:i\', date:\'@{constraint.startTimestamp}\')}',
    2: '{f:format.date(format:\'{settings.dateFormat} H:i\', date:\'@{constraint.endTimestamp}\')}'
  }"
/>

Backend Add/Edit Record Link

For the TYPO3 extension developer, If you want to create the link to Add/Edit a particular table’s record, you can use <be:link /> ViewHelper.

 

<!-- Create New Record Link -->
<be:link.newRecord table="table_name" returnUrl="foo/bar" uid="-17"/>
<a href="/typo3/index.php?route=/record/edit&edit[table_name][-17]=new&returnUrl=foo/bar">
    Add record
</a>

 

<!-- Create Edit Record Link -->
<be:link.editRecord uid="42" table="table_name" returnUrl="foo/bar" />
<a href="/typo3/index.php?route=/record/edit&edit[table_name][42]=edit&returnUrl=foo/bar">
    Edit record
</a>

 

<!-- Create Simple Page Link -->
<f:be.link route="web_ts" parameters="{id: 92}">Go to web_ts</f:be.link>

Display Style Infobox In Backend

At your TYPO3 custom backend module, Do you want to display a custom style information box? Just use <f:be.infobox /> ViewHelper.

 

<f:be.infobox title="Message title">your box content</f:be.infobox>

Inline TYPO3 Fluid Rendering

Use <f:inline /> TYPO3 Fluid ViewHelper.

<!-- Assign Variables from Your Controller -->
$view->assign('variable', 'value of my variable');
$view->assign('code', 'My variable: {variable}');

<!-- Render through TYPO3 Fluid Inline -->
{code -> f:inline()}

Assign Default Value To Variables

Do you want to create and assign default values? It will give assurance that your declared variable will always have some default values.

 

<!-- Giving variables default values if they are NULL -->
{class -> f:or(alternative: 'my-default') -> f:variable(name: 'class')}
{label -> f:or(alternative: 'No name') -> f:variable(name: 'label')}
{body -> f:or(alternative: 'Body not set') -> f:variable(name: 'body')}

 

<!-- Purpose: guarantee a value is filled for mandatory output -->
<div class="{class}">
  <h4>{label}</h4>
  <f:format.html>{body}</f:format.html>
</div>

Call Dynamic Sections Using Variables

In most cases, people always call static sections, which may create code redundancy. You should dynamically call your sections based on the value of your variables.

 

<!-- Using f:render to make "blocks" of output -->
Rendering into a variable and then using that variable can make the template more readable. This example is minimal; the bigger and more costly the rendering is, the more sense it makes to use this trick.

<f:section name="Icon">
  <span class="icon-{icon}"></span>
</f:section>

{f:render(section: 'Icon', arguments: {icon: 'twitter'}) -> f:variable(name: 'twitterIcon')}
{f:render(section: 'Icon', arguments: {icon: 'facebook'}) -> f:variable(name: 'facebookIcon')}

And use them as frequently as we want:

<div class="share">
  Share here!
  {twitterIcon -> f:format.raw()}
  {facebookIcon -> f:format.raw()}
</div>

<div class="also-share">
  Or here!
  {twitterIcon -> f:format.raw()}
  {facebookIcon -> f:format.raw()}
</div>

Easy Math Operation of TYPO3 Fluid

Do you want to perform simple mathematical operations within your TYPO3 fluid? Here it’s how;

 

<!-- Example 1. Simple math -->
<f:variable name="floatPercent" value="0.25" />
Percent done: {floatPercent * 100}%

<!-- Example 2. Manipulating Two Variables -->
<f:variable name="total" value="12" />
<f:variable name="done" value="3" />
Progress: {total - done} remaining.

<!-- Example 1. TypoScript Meets Fluid -->
<f:cObject typoscriptObjectPath="lib.math" data="20+22" />
lib.math = TEXT
lib.math {
  current = 1
  prioriCalc = 1
}

Ternary Condition in TYPO3 Fluid

For code redundancy, Consider using ternary conditions instead of many if/else statements.

 

<!-- Ternary condition -->
<f:variable name="variableToCheck" value="0" />
<f:variable name="option1" value="Option one" />
<f:variable name="option2" value="Option two" />
One of two options: {variableToCheck ? option1 : option2}
Fallback if variable not set: {option1 ? option1 : option2}

<!-- Outputs: -->
One of two options: Option two
Fallback if variable not set: Option one

<!-- Invalid: -->
{variableToCheck ? 'some text' : 'other text'}

Else..If Nested Conditions in Fluid

Maybe you don’t know, TYPO3 fluid provides to implement if..else...if nested conditions, Here is the example.

 

<!-- Else-if structure -->
Fluid can render "if" and "else" and we all know how that
works - but Fluid can also render "else-if" type structures:

<f:if condition="{var} > 100">
  <f:then> Overflow! </f:then>
  <f:else if="{var} > 90"> Danger! </f:else>
  <f:else if="{var} > 50"> Careful now. </f:else>
  <f:else> All good! </f:else>
</f:if>

Conditions for ViewHelper’s Output

In some situations, you may need to decide the based output of your used TYPO3 fluid viewhelpers. You can simply check within the If condition.

 

<f:if condition="<f:count subject='{post.comments}' /> > 0">
  <f:then>
    [...] Display comments here[...]
  </f:then>
  <f:else>
    No Comments found.
  </f:else>
</f:if>

What’s Grouped For Loop In Fluid?

Are you aware of <f:groupedFor /> TYPO3 Fluid ViewHelper? It’s interesting, consider below the practical code snippet.

 

<f:groupedFor each="{0: {name: 'apple', color: 'green'}, 1: {name: 'cherry', color: 'red'}, 2: {name: 'banana', color: 'yellow'}, 3: {name: 'strawberry', color: 'red'}}" as="fruitsOfThisColor" groupBy="color">
  <f:for each="{fruitsOfThisColor}" as="fruit">
    {fruit.name}
  </f:for>
</f:groupedFor>
<!-- Output: apple cherry strawberry banana -->

Understand For-loop Iteration in TYPO3 Fluid

Here is the list available for loop iteration which helps you to manipulate your TYPO3 fluid code.

 

<!-- List of For loop iteration -->
itemIteration.index (0 based index of the iteration)
itemIteration.cycle (the same as index, but starting from 1)
itemIteration.total (total number of items)
itemIteration.isFirst (TRUE for the first item in the iteration)
itemIteration.isLast (TRUE for the last item in the iteration)
itemIteration.isOdd (TRUE for odd cycles 1,3,5,...)
itemIteration.isEven (TRUE for even cycles 2,4,6,…)

<!-- How to use them -->
<ul>
  <f:for each="{values}" as="value" iteration="iterator">
    <li class="{f:if(condition:'{iterator.isOdd}',then:'odd',else:'even')}">{value}</li>
  </f:for>
</ul>

Display Records in Backend Module

TYPO3 Fluid provides a great ViewHelper to render a listing of your tables at your developed custom TYPO3 backend module.

 

<f:be.tableList tableName="pages" fieldList="{0: 'uid', 1: 'title'}"
    storagePid="1"
    levels="2"
    filter="foo"
    recordsPerPage="10"
    sortField="name"
    sortDescending="true"
    readOnly="true"
    enableClickMenu="false"
    clickTitleMode="info"
    />

How to Disable Parsing in TYPO3 Fluid?

Just simply set {parsing off} to completely disable parsing of TYPO3 fluid code. It will ignore compiling your fluid code throughout the fluid scope.

 

<!-- Parsing enabled modifier -->
{parsing off}
The fluid code will not execute eg., {myFluidVar} <f:sections /> etc.

Set Default Parameter in Fluid Partial

Using default parameters, you can define the default values of your particular TYPO3 fluid partial.

 

<!-- Default values when partial/section not found -->
<f:render partial="Missing" optional="1" default="Partial 1 not found" />

<f:render partial="AlsoMissing" optional="1">
  Partial 2 not found
</f:render>

<!-- Outputs: -->
Partial 1 not found
Partial 2 not found

How to Dynamically Call Partials in Fluid?

That’s relatively easy! Using define and assign variables, you can call dynamic partial into your TYPO3 fluid code.

 

<f:section name="RenderAsText">
  Text version of object
</f:section>

<f:section name="RenderAsImage">
  Image version of object
</f:section

<!-- Prepare Variable to Call Partial -->
<f:variable name="myType" value="Text" />

<!-- Rendering section with a partially dynamic name -->
<f:render section="RenderAs{myType}" />

<!-- Rendering section with optional parameter as Default-value -->
<f:render section="RenderAs{myType}" optional="1" /> 

A Whitespace Remover TYPO3 Fluid Helper

Using <f:spaceless /> TYPO3 Fluid ViewHelper, The white space within the code will be removed.

 

<!-- Removing meaningless whitespace -->
<f:spaceless>
  <div>
    <section>
      <p>
        Whitespace preserved inside tags
      </p>
      <p>But gets removed between tags</p>
    </section>
  </div>
</f:spaceless>

<!-- Outputs: -->
<div><section><p>
  Whitespace preserved inside tags
</p><p>But gets removed between tags</p></section></div>

Passing rendered Fluid to a part as variable

With "contentAs" on f:render you can make it render the tag content and pass this to the partial as a variable you name. This enables you to use f:render and partials to wrap output in different ways. Consider the following example:

 

<f:render partial="MySpecialWrap" contentAs="content">
  <div class="wrappable-content">
    <h4>This content can be wrapped</h4>
    <!-- Fluid can be used without restrictions here -->
  </div>
</f:render>

<!--And the following template source in the "MySpecialWrap" partial template:-->

<!-- In partial MySpecialWrap.html -->
<div class="outerwrap wrap-foobar">
  <section>
    {content -> f:format.raw()}
  </section>
</div>

Define & Use Namespaces (Globally)

With the following PHP code, you can globally register TYPO3 Fluid Namespaces.

 

// Globally registered fluid namespace
$GLOBALS['TYPO3_CONF_VARS']['SYS']['fluid']['namespaces']['my'] =['MyVendor\\MyExtension\\ViewHelpers'];
// Makes "my" a namespace in Fluid, e.g. "<my:foobar>" resolves
// to class MyVendor\MyExtension\ViewHelpers\FoobarViewHelper

$GLOBALS['TYPO3_CONF_VARS']['SYS']['fluid']['namespaces']['f'] = [
    'TYPO3Fluid\\Fluid\\ViewHelpers',
    'TYPO3\\CMS\\Fluid\\ViewHelpers'
];

AutoComplete TYPO3 Fluid Widget

Using <f:widget.autocomplete /> TYPO3 Fluid ViewHelper, you can quickly implement the auto-complete feature.

 

<!-- Create HTML Textbox -->
<input type="text" id="name" />

<!-- Initiate Autocomplete TYPO3 Fluid ViewHelper for create Textbox -->
<f:widget.autocomplete for="name" objects="{posts}" searchProperty="author">

<!-- Notes: You should add jQuery UI/UX library to use auto-complete feature -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.3/themes/base/jquery-ui.css" type="text/css" media="all" />
<link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" type="text/css" media="all" />

Throw Flash Message in TYPO3 Fluid

Let’s simply display standard bootstrap success/error messages into your TYPO3 custom backend module.

 

<!-- Simply Call ViewHelper -->
<f:flashMessages />

<!-- Output -->
<div class="typo3-messages">
   <div class="alert alert-info">
      <div class="media">
         <div class="media-left">
            <span class="fa-stack fa-lg">
               <i class="fa fa-circle fa-stack-2x"></i>
               <i class="fa fa-info fa-stack-1x"></i>
            </span>
         </div>

         <div class="media-body">
            <h4 class="alert-title">Info - Title for Info message</h4>
            <p class="alert-message">Message text here.</p>
         </div>
      </div>
   </div>
</div>

<!-- Write Custom-way Message -->

<f:flashMessages as="flashMessages">
   <dl class="messages">
      <f:for each="{flashMessages}" as="flashMessage">
         <dt>{flashMessage.code}</dt>
         <dd>{flashMessage.message}</dd>
      </f:for>
   </dl>
</f:flashMessages>

<!-- Output -->
 <dl class="messages">
    <dt>1013</dt>
    <dd>Some Warning Message.</dd>
</dl>

Call TypoScript into TYPO3 Fluid

I think you already know well about this, but still let me write for TYPO3 beginners ;)

 

<!-- Create TypoScript Object -->
lib.myObject = TEXT
lib.myObject.value = My TypoScript Object

<!-- Call TypoScript into Fluid -->
<f:cObject typoscriptObjectPath="lib.someLibObject" />

<!-- Output -->
My TypoScript Object

Localization in TYPO3 Fluid

One another simple one, Please make sure never to use static labels or text within your TYPO3 code. Let’s keep using TYPO3’s excellent localization feature.

 

<!-- Add new Label/Text to XLIFF - /typo3conf/ext/yourextension/Resources/Private/Languages/locallang.xlf -->
<trans-unit id="myKey"> <source>My Text</source> </trans-unit>

 

<!-- Call Language-wise Text from XLIFF file -->
<f:translate key="myKey" />

Printf in TYPO3 Fluid

As same as PHP’s printf, You can easily format your text using <f:format.printf /> TYPO3 Fluid ViewHelper.

 

<f:format.printf arguments="{number: 362525200}">%.3e</f:format.printf>
<f:format.printf arguments="{0: 3, 1: 'Kasper'}">%2$s is great, TYPO%1$d too. Yes, TYPO%1$d is great and so is %2$s!</f:format.printf>
{someText -> f:format.printf(arguments: {1: 'TYPO3'})}

Disable HTML Entity Escape in Fluid

Any variables you render will not need to use f:format.raw even if they contain special HTML entities. Useful when you render formats other than HTML; or when you completely trust (read: escaped before assigning to view) all your variables that get output.

 

<!-- Disabling HTML escaping for an entire file -->
{escaping off}

RenderingContextInterface - PHP to TYPO3 Fluid

Are you looking for your custom Renderable to manipulate stuff into your PHP?

 

<?php
use \TYPO3Fluid\Fluid\Core\Rendering\AbstractRenderable;
use \TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;

class MyRenderable extends AbstractRenderable
{
  public function render(RenderingContextInterface $renderingContext)
  {
    // Any PHP execution you want. The RenderingContext
    // will be the exact one that's active when you
    // render the renderable (and contains variables etc.)
    return 'My special rendering';
  }
}

<!-- then assign a view variable with an instance of MyRenderable -->
<f:render renderable="{renderable}" /> 

data-* Attribute in ViewHelpers

The "data" attribute on TagBasedViewHelpers. All ViewHelpers which use the AbstractTagBasedViewHelper parent class, or internally use the TagBuilder from Fluid, have the option of supporting arbitrary "data-*" attributes in two ways:

 

<!-- Prepare Data Attributes -->
Option 1. <v:h data-foobar="baz" data-biz="biz">content</v:h>
Option 2. <v:h data="{foobar: 'baz', biz: 'biz'}">content</v:h>

<!-- Output -->
Assuming "v:h" outputs a "div" tag, both examples output:
<div data-foobar="baz" data-biz="biz">content</div>

How to Create Dynamic Layouts?

At complex websites, you may require to create dynamic layouts. Consider this example;

 

<!-- Declare layout -->
<f:variable name=”layout” value=”home” />

<!-- Dynamic call your layout -->
<f:layout name="Custom{layout}" />

Formatting the Text in Fluid

Here is the list of hands TYPO3 fluid viewhelpers to format your text.

 

<!-- f:format.* -->
<f:format.date>{dateObject}</f:format.date>
<!-- Output: 1980-12-13 -->

<!-- f:format.case -->
<f:format.case>Some Text with miXed case</f:format.case>
<!-- Output: SOME TEXT WITH MIXED CASE -->

<!-- f:format.nl2br -->
<f:format.nl2br>{text_with_linebreaks}</f:format.nl2br>
<!-- Output: Text with line breaks replaced by <br /> -->

<!-- f:format.stripTags -->
<f:format.stripTags>Some Text with <b>Tags</b></f:format.stripTags>
<!-- Output: Some Text with Tags -->

Switch..Case To Avoid If..Else Complexity

Whenever you have too many conditions, try to avoid <f:if /> and Try to use <f:switch /> TYPO3 ViewHelper.

 

<f:switch expression=”{person.gender}”>
    <f:case value=”male”>Mr.</f:case>
    <f:case value=”female”>Mrs.</f:case>
    <f:defaultCase>Mr. / Mrs.</f:defaultCase>
</f:switch>

Cache Warmer to Compile TYPO3 Fluid Templates

Claus Due (aka @NamelessCoder) developed and maintained the following two TYPO3 fluid repositories.

(CLI) TYPO3 Fluid Template Precompiler

The command-line tool scans your TYPO3 site for and compiles it without rendering Fluid template files. Simply put, it warms up the Fluid template cache by parsing and compiling all templates without rendering them.

 

composer require namelesscoder/typo3-cms-fluid-precompiler
./vendor/bin/fluid-precompile
./vendor/bin/fluid-precompile --extension my_extension

(TYPO3 Extension) TYPO3 Fluid Template Precompiler

Provides a backend module and cache menu item to compile Fluid templates detected on the system without rendering the output. The backend module, in addition, provides very detailed information about the efficiency of individual template files.

How to Avoid Escaping Quotes in Fluid?

In Fluid, when you nest ViewHelper expressions, you are required to escape any nested quotes. This can quickly become difficult:

 

<!-- Bad Example -->
<f:render partial="Foobar" arguments="{
  label: '{f:if(condition: lll, then:
  \'{f:translate(key: \\'mylabel\\')}\',
  else: \'foobar\')}
}" />

<!-- Good Example -->
{f:translate(key: 'mylabel')
  -> f:if(condition: lll, else: 'foobar')
  -> f:variable(name: 'label')}
<f:render partial="Foobar" arguments="{label: label}" />

Reference of EXT.fluid_styled_content

While you are learning the structure and syntax of TYPO3 fluid, it’s always good to explore the TYPO3 core’s system extension EXT.fluid_styled_content.

Do You Know Fluid Powered TYPO3?

After an era of TemplaVoila, It seems the TYPO3 community largely accepted the FluidTYPO3 solution from - Of course, TYPO3 Fluid Man (Claus Due).

Fluid Powered TYPO3 is a family of TYPO3 extensions designed to boost productivity and flexibility when creating CMS templates.
- FluidTYPO3.org

Pattern Lab Fluid Engine: TYPO3 CMS export

Package which hooks into the Pattern Lab Fluid Edition to write your patterns as proper TYPO3 CMS Fluid template files into an extension folder - which then is more or less plug and play.

Meet TYPO3 Fluid + Atom Design (EXT.fluid_styleguide)

Fluid Components for TYPO3 enables frontend developers to implement consistent web designs with reusable components. Fluid Style Guide provides a dedicated front-end workshop and a powerful collaboration tool for all project stakeholders.

Converter > Fluid Tags to Inline Notation

To save your time, there is an online tool to convert your Fluid tags to inline notation.

Fluid Page Cache

Creates tags automatically for TYPO3's page cache, based on used variables in rendered Fluid templates on the current page.

EXT.fluid_components - Encapsulated Frontend Components

This TYPO3 extension puts frontend developers in a position to create encapsulated components in pure Fluid. By defining a clear interface (API) for the integration, frontend developers can implement components independent of backend developers. The goal is to create highly reusable presentational components with no side effects and aren't responsible for data acquisition.

EXT.fluid_fpdf - Automatically Create PDF from Fluid

This extension provides you with a complete set of ViewHelpers for dealing with FPDF by using Fluid. You can use the ViewHelpers easily in your own Extensions just by defining the fpdf-Namespace. Additionally, you can use the built-in plugin for displaying predefined PDF. This plugin offers you automatically all available PDFs.

IDEs Support TYPO3 Fluid

Fortunately, the lovely TYPO3 community and IDE’s people created helpful plugins to support all major IDEs.

PHPStorm - TYPO3 Fluid FOSS Support

This plugin is in an early draft stage. The project aims to provide a fully OpenSource plugin for the Fluid Template Language.

VS Code - TYPO3 Fluid Snippets

A collection of snippets for the TYPO3 Fluid syntax.

VS Code - TYPO3 Code Snippets

TYPO3 Code Snippet integration. Just type the letters 't3' to get a list of all available TYPO3 Code Snippets.

VS Code - TYPO3 VHS Snippets

A collection of snippets for the TYPO3 VHS: Fluid ViewHelpers

VS Code - flux-snippets

Snippets for TYPO3 Flux ViewHelpers

Atom - TYPO3 Fluid Language package

Adds syntax highlighting to TYPO3 Fluid tags and inline notations in Atom.

Popular TYPO3 Fluid Books

You can learn TYPO3 Fluid from available TYPO3 Extbase and Fluid Books. Explore Best TYPO3 Books at https://t3terminal.com/typo3-books and 12+ Best TYPO3 Books You'll Want to Read

TYPO3 Fluid Cheat Sheet

You can find the TYPO3 Fluid cheat sheet introducing you to an all-over structure of TYPO3 Fluid, useful Viewhelpers, etc. There are chances some of the code snippets may not work in the latest TYPO3 version. Hopefully, someone will update it to make it compatible with the latest  TYPO3 Extbase/Fluid Cheatsheet. Explore at 15 TYPO3 Cheat Sheets For Everyone!

Common TYPO3 Fluid Templates Method

Last but not least, although we have a powerful TYPO3 Fluid template engine, TYPO3 does not have a common TYPO3 template method. Of course, we have too much flexibility, and everyone has their own approach to create a TYPO3 template ;) I recommend reading the below article.

Wrapping-up!

Thanks for reading this long TYPO3 article. I hope you dig in-depth into TYPO3 fluid.

Do you know any tips and tricks for TYPO3 fluid? What’s your favorite tip from the above list? Do you have any questions or need help with TYPO3 fluid? I would love to receive your message in the comment box.

Have a Happy TYPO3 Fluiding!

Post Comment

Your email address will not be published. Required fields are marked *

×

Name is required!

Enter valid name

Valid email is required!

Enter valid email address

Comment is required!

Google Captcha Is Required!

Comments :

  • Hoja June 25, 2021 At 7:52 pm
    Nice one

Everything About TYPO3 PWA (Progressive Web Application)

Are you thinking and planning to integrate Modern TYPO3 PWA to your TYPO3 website? If yes, then Congratulations! In this article,…

How to Enable TYPO3 HTTPS?

How to Enable TYPO3 HTTPS?

Are you looking for an all-in-one article about TYPO3 + HTTPS? Then, You are at the right place. What & Why HTTPS, How to…

Learn TYPO3 Custom Elements with Core Ways

Learn TYPO3 Custom Elements with Core Ways

In your journey of TYPO3 development, you may get questions like, How should I develop TYPO3 custom elements? Which are available…

Stay up to date with our recent TYPO3 Blogs, news, & updates