Study guide · Fluid Basics
Understanding Fluid: templates, variables, ViewHelpers and components
Fluid is the template engine of TYPO3. On this page you build the templates for a music school website together with the integrator Mara. Afterwards you know how templates, layouts and partials work together, how to output variables safely, and how ViewHelpers, components and the Fluid commands work.
What Fluid is
Mara is building the website of the Lindenau Music School. The project is a Composer installation with TYPO3 14.3. The look lives in her own site package lindenau_site, and its Composer package is called lindenau/site.
Fluid turns templates and data into output, usually HTML. It is an independent open source project that TYPO3 uses in the frontend and in the backend. In the Model-View-Controller pattern, Fluid is the view, the presentation layer. The model holds the data. The controller handles the request and passes the data on to the view.
Since Fluid 5, which comes with TYPO3 14, the file extension fluid.html is common, for example Default.fluid.html. It is optional, and files ending in html are still found. If both exist in the same folder, the file with fluid.html wins.
Templates, layouts and partials
Fluid knows three kinds of files. Fluid always renders a template. It is the starting point and therefore required. Layouts and partials are optional.
- A layout is the frame around many templates. In Mara's project it holds the header and the footer of the page.
- A template fills this frame. It picks its layout with the ViewHelper
f:layoutand puts its content into sections, which are named blocks defined withf:section. - A partial is a small, reusable building block, for example a teaser for a course.
The layout inserts the sections of the template with f:render. A layout may only render sections and partials, it does not define sections of its own. Templates and partials may do both.
<!-- Layouts/Default.fluid.html -->
<header>Lindenau Music School</header>
<main><f:render section="Main" /></main>
<footer>4 Lindenau Market</footer>
<!-- Templates/Pages/Default.fluid.html -->
<f:layout name="Default" />
<f:section name="Main">
<h1>{page.title}</h1>
<f:render partial="Course/Teaser" arguments="{course: course}" />
</f:section>Who sees which variables?
- The layout works with the same variables as the template that uses it.
- A partial is self-contained. It only sees what the template passes with the argument
argumentswhen it includes the partial. The special value_allpasses all variables at once.
The code of Fluid 5 has one exception: Fluid passes the variable settings to partials automatically, unless you pass your own variable with that name. You must pass every other variable explicitly.
A partial can have sections too. If you give f:render both the partial and the section argument, it renders one section from a partial. Partials may render further partials themselves.
Where Fluid finds the files
The paths to the files are kept in three lists: templateRootPaths, layoutRootPaths and partialRootPaths. Each entry has a number as its key. Fluid checks the paths from the back: the highest key is searched first and the lowest last. The first matching file wins.
Mara uses her agency's base package under the key 10 and her site package under the key 20. Both contain a file Default.fluid.html. Fluid takes the file from path 20. This way Mara overrides single files on purpose. There is no error, and Fluid does not render both files.
In each path, Fluid first tries the extension fluid.html, then html, then no extension at all. This chain runs per path. So an old file ending in html in path 20 beats a fluid.html file in path 10.
Outputting variables
You output a variable by putting its name in curly braces. You reach nested values with a dot. This works for array keys and for object properties alike. Arrows or square brackets as in PHP do not exist for this.
<h1>{title}</h1>
<p>{course.name}, with {course.teacher.name}</p>
<p>Price: {prices.{duration}} euros</p>How does Fluid get an object property? For the name of a course, Fluid tries the methods getName(), isName() and hasName() in turn, and finally direct access to the property name. Objects with ArrayAccess and containers following the PSR standard ContainerInterface work too. If Fluid finds nothing, the output silently stays empty.
Dynamic keys: If the key itself is stored in a variable, you nest curly braces, as in the third line above. Without the inner braces, Fluid would read the fixed key duration and not the value of the variable.
Reserved names: You must not use the names _all, true, false and null for your own variables. Since Fluid 5 this applies to all variable names that start with an underscore. It only affects the first part of the name. An array key or a property with an underscore after the dot is still allowed.
<!-- invalid since Fluid 5 -->
{_temp}
{_somethingElse}
<!-- valid -->
{data._something}
{myArray._myKey}
{items.{index}}Safe output: escaping
By default, Fluid escapes every variable with the PHP function htmlspecialchars. A script tag becomes harmless text that is visible in the browser but never runs. This protects against cross-site scripting, XSS for short. Escaping does not depend on the file extension. It also applies in templates for plain text emails or JSON.
Sometimes you need unfiltered HTML. There are two ViewHelpers for this:
f:format.rawswitches escaping off completely for a value. It is only meant for HTML that is already safe.f:format.htmlis meant for text from the rich text editor. It sends the text through parseFunc, which converts links and only lets allowed tags through.
HTML comments do not protect anything. For Fluid, an HTML comment is ordinary text. Variables and ViewHelpers inside it are evaluated and executed. So a debug call inside an HTML comment still runs. Only the ViewHelper f:comment really removes content.
JavaScript and CSS in the template: Alpine.js and CSS also use curly braces. Fluid would read them as variables. Since Fluid 5, a CDATA section helps. Inside it, Fluid ignores ViewHelper tags and single curly braces. Only expressions in three curly braces are evaluated. Fluid removes the CDATA markers themselves from the output.
<![CDATA[
<div x-data="{ open: false }">
<button @click="open = !open">{{{label}}}</button>
</div>
]]>In the past, Fluid removed CDATA sections including their content, and some people used them to comment code out. Since TYPO3 14 that no longer works.
ViewHelpers and namespaces
ViewHelpers are the building blocks a template uses to process or output data. Behind every ViewHelper there is a PHP class. For components it is a Fluid template instead.
The ViewHelpers that ship with Fluid have the prefix f, for example f:for, f:if or f:link.page. This namespace is always available, you do not need to import it.
You can write every ViewHelper in two ways: as a tag like HTML, or inline in curly braces. Inline, you can chain ViewHelpers with an arrow, and the value is handed on from left to right.
<f:format.date format="d.m.Y">{course.start}</f:format.date>
{f:format.date(date: course.start, format: 'd.m.Y')}
{course.title -> f:format.trim()}Importing other ViewHelpers: For ViewHelpers from another extension you need a namespace declaration. It links a prefix to a PHP namespace. There are three ways:
- On the html tag with an xmlns attribute. This is valid XML, and IDEs can suggest tags from it. The extra attribute
data-namespace-typo3-fluidwith the value true makes sure the html tag itself is not output. - With the short notation in curly braces that starts with the word namespace.
- Globally in the file
Namespaces.phpin the folderConfiguration/Fluidof an extension. Then the prefix is available in all templates without an import.
<html xmlns:ls="http://typo3.org/ns/Lindenau/Site/ViewHelpers"
data-namespace-typo3-fluid="true">
{namespace news=GeorgRinger\News\ViewHelpers}The address in the xmlns attribute always starts with http, not https. With https, Fluid stops with an error, because the namespace declaration is invalid.
Global namespaces since TYPO3 14: In the past, you registered global namespaces in the system configuration, under SYS, fluid and namespaces in TYPO3_CONF_VARS. That is deprecated since TYPO3 14.1. Today every extension ships the file Namespaces.php.
<?php
// EXT:lindenau_site/Configuration/Fluid/Namespaces.php
return [
'ls' => ['Lindenau\\Site\\ViewHelpers'],
'lc' => ['Lindenau\\Site\\Components'],
];If two extensions register the same namespace, TYPO3 merges the files in loading order. There is no error, and nothing is ignored. If extension 2 depends on extension 1, it is loaded later, and its ViewHelpers with the same name win. This way one extension can override single ViewHelpers of another.
Conditions and loops
Conditions: The ViewHelper f:if only outputs content if its condition is true. With f:then and f:else you decide what appears in each case. For several cases in a row you do not need to nest: inside f:if you can add several f:else tags, each with its own if argument. A final f:else without if catches the rest.
<f:if condition="{course.full}">
<f:then>Waiting list</f:then>
<f:else if="{course.freeSeats} < 3">Almost full</f:else>
<f:else>Seats available</f:else>
</f:if>
<a class="{f:if(condition: isActive, then: 'active', else: '')}">Piano</a>The inline notation in the last line passes condition, then and else as arguments. It works well for CSS classes in attributes.
Loops: The ViewHelper f:for walks through a list and outputs its content for every element. It knows five arguments:
- each is the list, and as is the name under which the current element is available. Both are required.
- key sets the name of a variable for the key, for example in an associative array.
- reverse with the value true walks through the list backwards.
- iteration sets the name of an object with counters.
The iteration object offers seven values: index counts from 0, cycle counts from 1, and total is the number of elements. isFirst and isLast tell you whether the element is the first or the last one, and isEven and isOdd whether cycle is even or odd. It does not give you the previous or next element.
<f:for each="{courses}" as="course" key="id" iteration="i">
<p>{i.cycle}. {id}: {course.name}</p>
<f:if condition="{i.cycle} % 3 == 0 && !{i.isLast}">
<hr>
</f:if>
</f:for>Rendering partials and sections, defining arguments
The ViewHelper f:render includes partials and sections. Its most important arguments are these:
- partial loads a partial, section loads a section. Together they render a section from a partial.
- arguments passes variables, for example the course, or all variables with
_all. - optional with the value true means that a missing section causes no error. The output then stays empty. This is meant for sections that not every template defines, such as a sidebar.
- default provides a replacement text if the output stays empty, for example because an optional section is missing.
- contentAs turns the content between the opening and closing tag into a variable in the partial.
<f:render section="Sidebar" optional="true" />
<f:render partial="Box" arguments="{title: 'Registration'}" contentAs="content">
<p>The registration deadline is 30 September.</p>
</f:render>Declaring arguments: With the ViewHelper f:argument, a template, a partial or a component states which variables it expects. Only name and type are required. description, optional and default are optional.
<f:argument name="course" type="Lindenau\Site\Domain\Model\Course" />
<f:argument name="size" type="string" optional="{true}" default="m" />- Without optional, an argument is required. If it is missing in the call, Fluid throws an error.
- The type is checked when the value is passed. If the value does not fit and cannot be converted, there is an error as well.
- default only applies to optional arguments. A default value does not make a required argument optional.
Components: building blocks with a fixed interface
The course card of the music school appears on many pages. This is what Fluid components are for. They are reusable building blocks made of Fluid templates that you use like your own HTML tags. You do not need a PHP class for each component.
Compared to partials, components have two advantages. First, they do not need any partialRootPaths in the calling context. Second, they have fixed, typed arguments that you declare with f:argument. For components these declarations are the public interface and therefore required.
Component, partial or section? For a building block you need everywhere, use a component. For a part that only occurs inside one template, a section is enough.
Setting up: Before the first component you need a component collection. It links a folder of templates to a PHP namespace. In the past this always required a PHP class of your own, usually based on AbstractComponentCollection, for example in TYPO3 13. Since TYPO3 14.1, an entry in the file ComponentCollections.php in the folder Configuration/Fluid is enough. You only need the class for special cases.
<?php
// EXT:lindenau_site/Configuration/Fluid/ComponentCollections.php
return [
'Lindenau\\Site\\Components' => [
'templatePaths' => [
10 => 'EXT:lindenau_site/Resources/Private/Components',
],
],
];By default, each component lives in its own folder. That way you can put CSS and JavaScript right next to its template. Mara organises her components by Atomic Design, that is by complexity. There are small atoms such as a button, molecules such as the course card, and large organisms such as the page header. You address subfolders in the tag name with a dot.
A component declares its arguments and takes in the content between its tags with the ViewHelper f:slot.
<!-- Components/Molecule/CourseCard/CourseCard.fluid.html -->
<f:argument name="title" type="string" />
<f:argument name="variant" type="string" optional="{true}" default="default" />
<article class="card card--{variant}">
<h3>{title}</h3>
<f:slot />
</article>
<!-- call in a template -->
<lc:molecule.courseCard title="Piano for children">
Ages 6 and up, Tuesdays at 3 pm.
</lc:molecule.courseCard>The interface is strict. A component does not see any variables of the calling template. It only communicates through its arguments and slots. As with partials, the only exception in the code is the variable settings. If Mara also passes an argument class that the component does not declare, it is not accepted by default, and Fluid reports an error. Only the component collection can allow this, with the option additionalArgumentsAllowed.
Limits: Some ViewHelpers look for their parent ViewHelper in the rendering context. A text field made with f:form.textfield, for example, needs the surrounding f:form. A component, however, has its own context. That is why such ViewHelpers do not work reliably across component boundaries. Components should work without side effects.
Finding errors: comments, debugging and the command line
Comments: A comment that must not end up in the HTML belongs in the ViewHelper f:comment. Its content is not parsed and never appears in the output. That is why you can also use it to hide invalid Fluid syntax for a while. An HTML comment, in contrast, ends up in the page source, and Fluid executes the code inside it.
<f:comment>
New course card, work in progress:
<lc:molecule.courseKarte title="{course.title}"
</f:comment>Debugging: The ViewHelper f:debug shows you which variables are available in the template. With the variable _all as its content you see everything at once. The output is a collapsible tree with a title. That beats a plain echo or var_dump: maxDepth limits the depth, which is 8 by default, and you can hide certain classes or properties. PHP code does not belong in Fluid templates anyway.
By default, f:debug puts its output at the top of the page. With the argument inline set to true, it appears where the tag is. With title you give the output a heading.
<f:debug title="Course list" inline="true">{_all}</f:debug>Fluid on the command line: TYPO3 ships four commands in the namespace fluid. There is no command that repairs templates.
- fluid:analyze checks the project's templates for syntax errors and deprecated functionality, the deprecations. For example, it reports variables that start with an underscore.
- fluid:cache:warmup compiles the templates it finds in advance. This pays off after a deployment, so that the first visitor does not have to wait for Fluid to compile the templates.
- fluid:namespaces lists the globally registered namespaces.
- fluid:schema:generate writes XSD files for all available ViewHelpers to the folder
var/transient. Since TYPO3 14.2 this includes components. Your IDE then suggests tags and arguments.
vendor/bin/typo3 fluid:analyze
vendor/bin/typo3 fluid:cache:warmupKey points
- Fluid is the template engine of TYPO3 and the view in the MVC pattern.
- Fluid always renders a template. The layout is the frame, partials are reusable pieces.
- The layout sees all variables of the template. A partial only gets what you pass with arguments, except for settings.
- The highest key in the root paths is searched first.
- Fluid escapes all output. The raw ViewHelper turns that off and is an XSS hole for input from visitors.
- Since Fluid 5, variable names with a leading underscore are reserved, and CDATA with three curly braces keeps Fluid apart from JavaScript.
- Since TYPO3 14.1, an extension registers global namespaces in the file Namespaces.php.
- Components have fixed, typed arguments, take content through a slot and need no partial paths.
- The comment ViewHelper removes content before parsing, an HTML comment does not.
- fluid:analyze checks, fluid:cache:warmup precompiles, and fluid:schema:generate creates XSD files.
Terms
- Component
- Reusable building block made of a Fluid template with fixed arguments, used like a tag of its own.
- Component collection
- Links a folder of components to a namespace, since TYPO3 14.1 also through a configuration file.
- Escaping
- Masking HTML special characters so that text is not executed as code.
- Layout
- Frame of shared markup that inserts the sections of a template.
- Partial
- Small, reusable piece that only sees the variables passed to it.
- Section
- Named block in a template or partial.
- Slot
- Place in a component where the content between its tags appears.
- ViewHelper
- Building block in a template that processes or outputs data, usually a PHP class.
- XSD
- Schema file that lets an IDE suggest tags and arguments.
- XSS
- Cross-site scripting, malicious code injected into the browser.