Fluid is a PHP template engine and is the de facto standard for any HTML-based
output in the TYPO3 CMS. However, it is not dependent on TYPO3 and can be used
in any PHP project.
If using Fluid in combination with TYPO3 CMS, a look at the documentation of
Fluid Styled Content
can be worth a look.
Fluid is a PHP-based templating engine for web projects. In contrast to other
templating engines, it uses an XML-based syntax in its templates, which allows
template authors to apply their existing HTML knowledge in Fluid templates.
Fluid originated in the TYPO3 and Neos ecosystem before it was extracted
from these projects into a separate PHP package. While its main usage nowadays
is within TYPO3 projects, it can also be used as an independent templating
language in PHP projects.
In Fluid, all dynamic output is escaped by default, which makes the templating
engine secure by default. This prevents common XSS (Cross Site Scripting)
mistakes that can easily happen in HTML templates.
Fluid comes with a range of so-called ViewHelpers that allow various formatting
and output modification directly in the template. Custom logic can be added
by providing custom ViewHelper implementations through a straightforward
PHP API.
Installation
Fluid is distributed through composer. It can be added to your project by
executing the following command:
Discover the intricacies of variables in Fluid templates
File Structure
Learn about the different template file types as well as their use cases
and rules.
ViewHelpers
Learn about the different flavors of ViewHelpers and how to use them in your
templates.
Components
Learn how to configure, define and render components in your Fluid
templates.
Getting Started
Before you can start writing your own Fluid template files, you first need to make
sure that the environment is set up properly. If you are using a framework like
TYPO3, this might already be the case. However, if you are starting from scratch, you
need to do some preparations in PHP first:
Creating a View
Fluid comes with a bunch of PHP classes that allow you to open Fluid template files,
assign variables to them and then render them to get the desired result. To get started,
you need to be aware of TemplateView, the RenderingContext and TemplatePaths.
The TemplateView is the "view part" in the Model-View-Controller pattern. It is the
main API between your PHP application and the template file. Each TemplateView renders
exactly one template file (which can have a layout file and can also include other templates,
called partials).
The RenderingContext is kind of self-describing: It contains all context necessary to
render the template. At first, you might only use it to define the path to your Fluid
template file via ...
TemplatePaths, which is usually a sub-object of the rendering context. It provides multiple
ways to define the location(s) to your template files.
To render a template file called MyTemplate.html, which is located in /path/to/templates/,
you first create a TemplateView object:
$view = new \TYPO3Fluid\Fluid\View\TemplateView();
Copied!
Then you can access the TemplatePaths and provide the location to your template file, for
example like this:
Within Fluid templates, it is possible to use some controll structures to implement simple
logic. It is also possible to perform some data modification. Both is possible by using
so-called ViewHelpers.
With the <f:if> ViewHelper, you can implement simple if-then-else
logic, for example:
If you encounter a problem in your template or you just want to know what
data is available, you can use the <f:debug> ViewHelper:
<f:debug>{myVariable}</f:debug>
Copied!
If you want to get an overview of all available variables, you can use the special
variable {_all}:
<f:debug>{_all}</f:debug>
Copied!
Variables
Assign a variable in PHP:
$this->view->assign('title', 'An example title');
Copied!
Output it in a Fluid template:
<h1>{title}</h1>
Copied!
The result:
<h1>An example title</h1>
Copied!
In the template's HTML code, wrap the variable name into curly
braces to output it.
Special _all Variable
The special variable {_all} contains an array with all variables that are currently
defined in your template. This can be helpful for debugging purposes, but also if you
want to pass all variables to a partial:
<f:renderpartial="MyPartial"arguments="{_all}" />
Copied!
However, be advised that this makes it more difficult to re-use partials, so it's recommend
to only pass the variables that are actually needed in the partial.
Variable Scopes
Each Fluid template, partial and section has its own variable scope. For templates,
these variables are set via the PHP API, for partials and sections the <f:render>
ViewHelper has a arguments argument to provide variables.
Inside templates, partials and sections there are two variable scopes: global
variables and local variables. Local variables are created by ViewHelpers that
provide additional variables to their child nodes. Local variables are only valid
in their appropriate context and don't leak out to the whole template.
For example, <f:alias> and <f:for> create local variables:
<f:foreach="{items}"as="item"><!-- {item} is valid here --></f:for><!-- {item} is no longer valid here --><f:aliasmap="{item: myObject.sub.item}"><!-- {item} is valid here --></f:for><!-- {item} is no longer valid here -->
Copied!
If a global variable uses the same name as a local value, the state of the global
value will be restored when the local variable is invalidated:
<f:variablename="item"value="global item" /><!-- {item} is "global item" --><f:foreach="{0: 'local item'}"as="item"><!-- {item} is "local item" --></f:for><!-- {item} is "global item" -->
Copied!
If a variable is created in a local block, for example by using the <f:variable>
ViewHelper, that variable is treated as a global variable, so it will leak out of
the scope:
<f:foreach="{0: 'first', 1: 'second'}"as="item"><f:variablename="lastItem"value="{item}" /></f:for><!-- {lastItem} is "second" -->
Copied!
If a global variable is created inside a local scope and uses the same name as a local
variable, it will still leak out of the scope and will also be valid inside the scope:
<f:foreach="{0: 'first', 1: 'second'}"as="item"><!-- {item} is "first" or "second" --><f:variablename="item"value="overwritten" /><!-- {item} is "overwritten" --></f:for><!-- {item} is "overwritten" -->
Copied!
Fluid Template File Structure
Fluid knows three different types of template files: Templates, Layouts
and Partials. Templates are always the starting point and thus are always
required, while both Partials and Layouts are optional. However, these can be
very helpful to improve the structure of your templates and can avoid duplicate
code, which makes maintenance much easier.
Layouts are a flexible method to reuse HTML markup that should wrap around
multiple template files. You could for example extract your header and footer
markup to a layout file and only keep the content in-between in your template.
Layouts automatically have access to all variables defined within the template.
Partials are an easy way to abstract and reuse code snippets in your templates.
They don't have access to all template variables, instead the required variables
need to be provided to the partial when it is used.
Note
When referring to these files, the names are used with an uppercase starting
letter (i.e., the name of the type). When referring to any file containing Fluid, the
term "templates" is sometimes used (i.e., lowercase starting letter), and in this
case refers to all of the above types as a group.
Inside Templates and Partials, the <f:section> ViewHelper
can be used to define sections that can be rendered using the
<f:render> ViewHelper. Both Templates and Partials
may define and render sections, but Layouts may only render sections and partials.
The API
Fluid uses a class called TemplatePaths which is part of the view's RenderingContext
and can resolve and deliver template file paths and sources.
In order to change the default paths you can set new ones in the TemplatePaths
associated with your RenderingContext:
// Create your view
$view = new \TYPO3Fluid\Fluid\View\TemplateView();
// set up paths object with arrays of paths with files
$paths = $view->getRenderingContext()->getTemplatePaths();
$paths->setTemplateRootPaths(['/path/to/templates/']);
$paths->setLayoutRootPaths(['/path/to/layouts/']);
$paths->setPartialRootPaths(['/path/to/partials/']);
Copied!
Note that paths are always defined as arrays. In the default TemplatePaths
implementation, Fluid supports lookups in multiple template file locations -
which is very useful if you are rendering template files from another package
and wish to replace just a few template files. By adding your own template files
path last in the paths arrays, Fluid will check those paths first.
Templates
In Fluid, Templates can be referenced in two different ways:
Directly by file path and filename
Resolved using a controller name and action (and format)
Direct usage is of course done by simply setting the full path to the template
file that must be rendered; no magic in that.
In an MVC (model-view-controller) context the latter can be used to implement a
universal way to resolve the template files so you do not have to set the file
path and filename for each file you want to render. In this case, Fluid will
resolve template by using the pattern {$templateRootPath}/{$controllerName}/{$actionName}.{$format}
with all of these variables coming directly from the TemplatePaths instance -
which means that by filling the TemplatePaths instance with information about
your MVC context you can have Fluid automatically resolve the paths of template
files associated with controller actions.
Templates may or may not use a layout. The layout can be indicated by the use of
<f:layout name="LayoutName" /> in the template source.
Fluid will behave slightly differently when a template uses a layout and when it
does not:
When no Layout is used, the template is rendered directly and will output
everything not contained in an <f:section>
When a Layout is used, the Template itself is not rendered directly.
Instead, the Template defines any number of <f:section> containers which
contain the pieces that will be rendered from the layout using <f:render>
You can choose freely between using a layout and not using one - even when
rendering templates in an MVC context, some templates might use layouts and
others might not. Whether or not you use layouts of course depends on the
design you are trying to convey.
Layouts are as the name implies a layout for composing the individual bits of
the design. When your design uses a shared HTML design with just smaller pieces
being interchangeable (which most web applications do) your layout can contain
the container HTML and the individual templates can define the smaller design
bits that get used by the layout.
The template in this case defines a number of <f:section> containers which the
layout renders with <f:render>. In application terms, the rendering engine
switches to the layout when it detects one and renders it while preserving the
template's context of controller name and action name.
Partials are the smallest design bits that you can use when you need to have
reusable bits that can be rendered from multiple templates, layouts or even
other partials. To name a few types of design bits that make sense as partials:
Address renderings
Lists rendered from arrays
Article metadata blocks
Structured data markup
The trick with partials is they can expect a generically named but predictably
structured object (such as an Address domain object instance, an array of string
values, etc). When rendering the Partial, the data can then be picked from any
source that fulfills the requirements. In the example of an Address, such an
object might be found on both a Person and a Company, in which case we can
render the same partial but with different sources:
The partial then expects the variable {address} with all the properties
required to render an address; street, city, etc.
A partial may or may not contain <f:section>. If it does contain <f:section>
containers, then the contents of those containers can be rendered anywhere,
including inside the Partial itself, by <f:render partial="NameOfPartial" section="NameOfSection" />.
Partials without sections can be rendered by just
<f:render partial="NameOfPartial" /> (with or without arguments).
Templates, layouts and partials can define requirements for variables by
using the <f:argument> ViewHelper. It is
possible to define a variable as required or optional. Also, a specific
type can be required. If any of the constraints don't match the supplied
data, an exception is thrown.
In effect, this allows you to define an API for template files, which
improves both documentation and reusability of template files, especially
partials.
ViewHelpers
How to use ViewHelpers
ViewHelpers are special tags in the template which provide more complex
functionality such as loops or special formatting of values. The functionality
of a ViewHelper is implemented in PHP, and each ViewHelper has its own PHP class.
Within Fluid, the ViewHelper is used as a special HTML element with a namespace
prefix, for example the namespace prefix f is used for ViewHelpers from the
built-in Fluid namespace:
The f namespace is already defined, but can be explicitly specified to
improve IDE autocompletion.
Custom ViewHelpers use their own namespace, in this case blog:
<blog:myViewHelperargument1="something" />
Copied!
The namespace needs to be registered explicitly, see the next section.
ViewHelpers can accept input values both from their tag content and from arguments,
which are specified as tag attributes. The ViewHelper syntax is documented
in Fluid ViewHelper Syntax.
Registering/importing ViewHelpers
When you need to use third-party ViewHelpers in your templates, there are multiple
equally valid options.
You can use the PHP API to register a namespace that should be
available in all template files without further importing:
$view = new TemplateView();
$view->getRenderingContext()->getViewHelperResolver()
->addNamespace('foo', 'Vendor\\Foo\\ViewHelpers');
Copied!
To make a namespace only available in one template file, the following syntax
variants are possible:
Once you have registered/imported the ViewHelper collection, you can start using
it in your templates via the namespace alias you used during registration (in this
example: foo is the alias name).
Deprecated since version 4.2
It was possible to define a namespace in a template and then use it in a
referenced partial without redeclaring it in the partial. This behavior
(inheritance of ViewHelper namespaces) is deprecated and will no longer
work in Fluid 5.
Tag-based ViewHelpers
Tag-based ViewHelpers are special ViewHelpers that extend a different base class called
AbstractTagBasedViewHelper.
The purpose of these special ViewHelpers is to generate a HTML tag based on the supplied
arguments and content.
Tag-based ViewHelpers provide default arguments that help enhancing the generated HTML
tag:
An array of data-* attributes can be provided via the data argument
An array of aria-* attributes can be provided via the aria argument
An array of additional HTML attributes can be provided via the additionalAttributes
argument
You can also supply arbitrary arguments that don't need to be defined by the ViewHelper,
which will be added to the generated HTML tag automatically
Condition ViewHelpers are another special type of ViewHelper that allow to check for certain
conditions within a template. They extend from a different base class called
AbstractConditionViewHelper.
All condition ViewHelpers have in common that a then and one or multiple else clauses
can be defined. There are multiple ways to do this, and almost all combinations imaginable
are possible.
The generic and most used condition ViewHelper is <f:if>.
then/else as argument
You can define then and else as ViewHelper arguments:
<!-- then and else --><f:ifcondition="{myVar} == 'test'"then="variable is test"else="variable is something else" />
{f:if(condition: '{myVar} == \'test\'', then: 'variable is test', else: 'variable is something else')}
<!-- only then --><f:ifcondition="{myVar} == 'test'"then="variable is test" />
{f:if(condition: '{myVar} == \'test\'', then: 'variable is test')}
<!-- only else --><f:ifcondition="{myVar} == 'test'"else="variable is something else" />
{f:if(condition: '{myVar} == \'test\'', else: 'variable is something else')}
Copied!
then/else as child ViewHelpers
With the tag syntax, it is also possible to define more advanced conditions:
<!-- only then --><f:ifcondition="{myVar} == 'test'">
variable is test
</f:if><!-- then and else --><f:ifcondition="{myVar} == 'test'"><f:then>variable is test</f:then><f:else>variable is something else</f:else></f:if><!-- only else --><f:ifcondition="{myVar} == 'test'"><f:else>variable is something else</f:else></f:if><!-- multiple else-if --><f:ifcondition="{myVar} == 'test'"><f:then>variable is test</f:then><f:elseif="{myVar} == 'foo'">variable is foo</f:else><f:elseif="{myVar} == 'bar'">variable is bar</f:else><f:else>variable is something else</f:else></f:if>
Copied!
Get verdict by omitting then/else
New in version Fluid 4.1
If neither then nor else in any of the accepted forms is specified, the ViewHelper
returns the verdict of the condition as boolean. This value can be used for further
processing in the template, for example in complex conditions:
<!-- The variable will contain the result of the condition as boolean --><f:variablename="isEitherTestOrFoo"value="{f:if(condition: '{myVar} == \'test\' || {myVar} == \'foo\'')}"
/><!-- This example combines two custom condition ViewHelpers to a larger condition --><f:ifcondition="{my:customCondition(value: variableToCheck)} || {my:otherCondition(value: variableToCheck)}">
...
</f:if>
<!-- disabled attribute is set if either no first name or no last name is set --><my:tagBaseddisabled="{f:if(condition: '!{firstName} || !{lastName}')}"
/>
Copied!
Understanding ViewHelpers
All built-in ViewHelpers are documented in the ViewHelper Reference.
If you want to learn more about a specific ViewHelper or if you are using a custom
ViewHelper that isn't documented, you can take a look at the ViewHelper source code, written
in PHP.
Each ViewHelper has a corresponding PHP file, which contains a class that describes the
ViewHelper's arguments as well as its behavior in the template. Such classes are usually placed
in the Vendor\Package\ViewHelpers PHP namespace (where Vendor and Package are placeholders
for actual values) and follow the following naming convention:
f:format.raw results from the PHP class TYPO3Fluid\Fluid\ViewHelpers\Format\RawViewHelper
f:render results from the PHP class TYPO3Fluid\Fluid\ViewHelpers\RenderViewHelper
mypkg:custom.specialFormat results from the PHP class
My\Package\ViewHelpers\Custom\SpecialFormatViewHelper, assuming you added
xmlns:mpkg="http://typo3.org/ns/My/Package/ViewHelpers" or an alternative namespace
registration (see above).
Note that these rules only apply to normal ViewHelpers. For Components,
different rules apply.
The arguments a ViewHelper supports will be verbosely registered in the
initializeArguments() function of each ViewHelper class. Inspect this method to
see the names, types, descriptions, required flags and default values of all
attributes. An example argument definition looks like this:
publicfunctioninitializeArguments(){
$this->registerArgument('myArgument', 'boolean', 'If true, makes ViewHelper do foobar', false, false);
}
Copied!
Which translated to human terms means that we:
Register an argument named myArgument
Specify that it must be a boolean value or an expression resulting in a
boolean value (see Boolean conditions).
Other valid types are integer, string, float, array, object, DateTime and
other class names. The array of syntax can also be used, for example string[] or
Vendor\Package\MyClass[]. Multiple type options (= union types) can be specified by
separating them with a |, for example array|string.
Describe the argument's behavior in simple terms.
Define that the argument is not required (the 4th argument is false).
Set a default value of false (5th argument), if the argument is not
provided when calling the ViewHelper.
The ViewHelper itself would then be callable like this:
What the ViewHelper does with its input values is determined by the render() method in the ViewHelper class.
Components
New in version Fluid 4.3
Fluid's components are custom HTML-like tags based on Fluid templates that you can
reuse throughout your project. The concept is similar to popular frontend
frameworks like React and Vue or native Web Components, but they are server-rendered
by PHP.
At first glance, components are quite similar to partials: They are separate
template files that can be reused by other templates and thus avoid duplicate code.
However, they have two major advantages over partials, which make them much
more reusable:
Components can be used in any template, without manual configuration of
partialRootPaths in the template's rendering context.
Components have strict, typed definitions of arguments via their API (using the
<f:argument> ViewHelper), making them less
error-prone.
Warning
ViewHelpers that depend on the RenderingContext to find parent ViewHelpers,
expecially ViewHelpers like the TYPO3 specific
Form.textfield ViewHelper <f:form.textfield>
will not work, especially across multiple components.
The purpose of components is to be as reusable as possible. They should avoid
side-effects and all communication should ideally be one-way through their arguments
or slots.
Basic Setup
Before templates can be used as components, an initial setup process is
necessary: A ComponentCollection class is required, which allows you to
define which template folder contains your component templates. Fluid comes with
a base implementation in AbstractComponentCollection that already
covers the most common use cases. However, it is also possible to
customize the component context, such as providing global settings that
should be available in all component templates.
In the context of TYPO3, it is recommend to place your ComponentCollection into
EXT:my_sitepackage/Classes/Components/ComponentCollection.php. Components are usually
created in Resources/Private/Components/ in your sitepackage extension. The path
can be specified in your ComponentCollection (see code example above) via
The default implementation in AbstractComponentCollection specifies that
each component template needs to be placed in a separate folder. The purpose of this
decision is that related asset files (such as CSS or JS) can be placed right
next to the component's template, which fosters a modular frontend
architecture and enables easier refactoring.
Note
In the following examples, atomic design
is used to demonstrate that components can be structured in subfolders.
You can use any structure that works best for your project.
The <f:slot> ViewHelper can be used to access the
children of the component tag.
Using Components
Once the ComponentCollection class exists and the component template has
been created, it can be imported into any Fluid template and component tags
can be used:
In the context of TYPO3, you can also define a global Fluid namespace, which allows
to use your components across the whole project without importing them into
each template file manually:
An alternative approach that prevents the need for nesting would be to call the atom.icon
component from within the atom.button component and to extend its argument API accordingly:
IDE autocomplete for all available components (and their attributes) via XSD files,
similar to ViewHelpers, is not implemented yet, but is planned for a future release.
Providing Context
Sometimes it might be helpful to provide some global settings to all components
within one component collection. One common use case could be to provide design
tokens from a JSON file to your components.
AbstractComponentCollection provides getAdditionalVariables(),
which allows you to do just that:
ComponentCollection.php
namespaceVendor\MyPackage\Components;
useTYPO3Fluid\Fluid\Core\Component\AbstractComponentCollection;
finalclassComponentCollectionextendsAbstractComponentCollection{
// Runtime cache to prevent reading/parsing the JSON file multiple times// this is not mandatory, but increases performance with multiple componentsprivate ?array $designTokens = null;
// ...publicfunctiongetAdditionalVariables(string $viewHelperName): array{
$this->designTokens ??= json_decode(file_get_contents('path/to/designTokens.json'), true);
return [
'designTokens' => $this->designTokens,
];
}
}
Copied!
In your component templates you would then be able to access those tokens:
Please use this approach with care because one of the key concepts of components
is their argument contract.
By default, components only accept arguments that are defined explicitly via
the <f:argument> ViewHelper. However, there might
be use cases where you would like to accept arbitrary arguments.
This is possible by defining additionalArgumentsAllowed() in your
ComponentCollection implementation (in this example for all components
in the collection):
In the component, {something} would be available as an additional variable.
Alternative Folder Structure
If you want to define an alternative folder structure to the default
{componentName}/{componentName}.html, you can do so by providing a custom
implementation of resolveTemplateName() in your ComponentCollection.
The following example skips the additional folder per component:
<my:atom.button> will then be resolved to path/to/Components/Atom/Button.html.
path/to/Components/
Atom
Button.html
Fluid Syntax
Variables
Overview of Fluid's syntax to access variables
Expressions
Overview of Fluid's array/object syntax and included expressions
Escaping
Overview of Fluid's escaping possibilities within the inline syntax as well as
approaches to deal with syntax collisions of JS and CSS
Conditions & Booleans
Overview of Fluid's condition capabilities and its handling of boolean values
ViewHelpers
Overview of Fluid's inline and tag syntax for ViewHelpers as well as namespaces
Comments
Fluid's commenting capabilities
Fluid Syntax: Variables
Accessing variables
Variables in Fluid can be accessed with the following braces {} syntax:
<h1>{title}</h1>
Copied!
Arrays and objects
Use the dot character . to access array keys:
<p>{data.0}, {data.1}</p>
Copied!
This also works for object properties:
<p>{product.name}: {product.price}</p>
Copied!
These object properties are obtained by evaluating a fallback chain,
which includes various getter methods as well as direct property access.
For example, the following PHP-equivalents would be checked for {product.name}:
Also, both ArrayAccess and the PSR ContainerInterface are supported.
Dynamic keys/properties
It is possible to access array or object values by a dynamic index:
{myArray.{myIndex}}
Copied!
Reserved variable names
The following variable names are reserved and must not be used:
_all
true
false
null
Fluid Syntax: Expressions
The syntax for expressions in Fluid is a mix between plain
variable access (e. g. {variable}) and ViewHelper usage in inline mode
(e.g. {myArray -> f:count()}).
Fluid's expression syntax is extendable, but in most circumstances the
following features are available. See
Expression Nodes
to learn how to extend Fluid's expression behavior.
Objects and arrays
Within a ViewHelper call, arrays (with numeric keys) and object structures can be
defined inline:
Trailing commas are valid syntax and are recommended to create cleaner diffs in
version control systems.
Type casting
The as expression can be used to convert variables to a different type.
For example, {myPossiblyArray as array} will ensure that {myPossiblyArray}
is accessed as an array even if it is of a different type such as null, which is
useful if you are passing a value to a ViewHelper like <f:for>
that requires an array as input. Other supported types for casting are: integer,
boolean, string, float and DateTime.
If you use as array on a string that contains comma-separated values, the
string is split at each comma, similar to PHP's
explode function.
Math expressions
Fluid supports basic math operations. For myNumber = 6, the following expressions
result in:
Fluid supports the ternary operator for variables, allowing you to switch
between two variables based on the value of a variable. For static values,
like a string, this is not supported.
{checkVariable ? thenVariable : elseVariable}
Copied!
If {checkVariable} evaluates to true, variable {thenVariable} is
used, otherwise variable {elseVariable} is used.
Fluid Syntax: Escaping
Escaping behavior in inline syntax
At a certain nesting level, single quotes ' required for the
inline syntax need to be escaped with a backslash:
While escaping cannot be avoided in all cases, alternatives should always be
preferred to improve the readability of templates. Depending on the use cases, there
are different approaches to achieve this.
Passing variables to inline ViewHelpers
If only a variable is passed as a ViewHelper argument, the single quotes '
and curly braces {} can be omitted:
{f:format.case(mode: 'upper', value: myVariable)}
Copied!
Using ViewHelper chaining if possible
Many ViewHelpers that perform changes on a single value also accept that value as a
child value. This allows a much cleaner syntax if you combine multiple ViewHelpers for
one value:
While it is generally advisable to avoid inline JavaScript and CSS code within
Fluid templates, sometimes it may be unavoidable. This can lead to collisions
between Fluid's inline or variable syntax and the curly braces {}
syntax characters used in JavaScript and CSS.
There are two approaches how these collisions can be avoided:
f:format.json ViewHelper
If your goal is to create JSON in your template, you can create an object in Fluid
and then use the <f:format.json> ViewHelper
to generate valid JSON:
<divdata-value="{f:format.json(value: {foo: 'bar', bar: 'baz'})}">
Copied!
This can also be used directly in JavaScript code that doesn't use any curly braces
itself:
<script>let data = {f:format.json(value: {foo: 'bar', bar: 'baz'}) -> f:format.raw()};
Copied!
CDATA sections
New in version Fluid 5.0
CDATA sections can be used to avoid syntax collisions. For Fluid 4 and below,
workarounds are documented in older versions of this documentation.
CDATA sections can be used in Fluid templates to partially switch off the Fluid
parser and to alter the syntax for variables, expressions and inline ViewHelpers.
This makes it possible to mix CSS or JS with certain Fluid features.
The following syntax rules apply to text wrapped with <![CDATA[ ]]> in
Fluid templates:
ViewHelper tag syntax is ignored: ViewHelper tags will not be interpreted and
will just remain as-is.
ViewHelper inline syntax, variables and expressions are only interpreted if
they are using three curly braces {{{ }}} instead of just one { }.
The <![CDATA[ ]]> keyword will be removed. If you want the CDATA to remain
in the output, consider using the
<f:format.cdata> ViewHelper.
Note that there might still be syntax overlaps if your CSS or JS uses three
curly braces that shouldn't be interpreted by Fluid.
Boolean conditions are expressions that evaluate to true or false.
Boolean conditions can be used as ViewHelper arguments, whenever the datatype
boolean is given, e.g. in the condition argument of the
<f:if> ViewHelper.
The expression can be a variable, which is evaluated as follows:
Number: Evaluates to true if it is not0.
Array: Evaluates to true if it contains at least one element.
The expression can be a statement consisting of: term1 operator term2, for
example {variable} > 3.
The operator can be one of the following: >, >=, <, <=,
==, ===, !=, !==, or %.
The previous expressions can be combined with || (logical OR) or && (logical AND).
If a ViewHelper argument is defined as boolean, it is also possible to provide
values of different types, which will then be implicitly converted to a boolean:
<f:rendersection="MySection"optional="1" />
Copied!
This can be used to remain compatible to Fluid 2, which did not support boolean literals
in all cases.
Fluid Syntax: ViewHelpers
ViewHelper calls can be written using two distinct syntaxes—tag syntax and inline syntax.
ViewHelpers are grouped into namespaces and can be organized in folders.
When a ViewHelper is called in a template, you specify the namespace identifier, followed
by a colon and the path to the ViewHelper, separated by dots:
namespace:folder.subFolder.name
Copied!
Tag syntax
The tag syntax works just like HTML or XML. Tags can either be self-closing or can have
a content, which can include other HTML tags or ViewHelper calls.
<!-- self-closing --><f:constantname="\Vendor\Package\Class::CONSTANT" /><!-- text content --><f:format.casemode="upper">lowercase</f:format.case><!-- other ViewHelpers as content --><f:switchexpression="{myVariable}"><f:casevalue="foo">Variable is foo</f:case><f:casevalue="bar">Variable is bar</f:case><f:defaultCase>Variable is something else</f:defaultCase></f:switch><!-- Nested format ViewHelpers --><f:format.trim><f:replacesearch="foo"replace="bar"><f:format.casemode="upper">
{myString}
</f:format.case></f:replace></f:format.trim>
Copied!
Inline syntax
Tip
There is an online tool to convert tag-based syntax to inline syntax:
Fluid Converter
The inline syntax works using curly braces {}. Most ViewHelpers can also be used with
the inline syntax, although the syntax might get more complicated depending on the use case.
Depending on the situation, it might be better to use the inline syntax instead of the
tag syntax and vice versa. Here is a more complex example that shows where the inline
syntax is still possible, but might make things more complicated:
Please note that, in chained inline notation, the f:if ViewHelpers should not
use their usual then or else attributes, as they would directly output
their value and thus break the chain!
ViewHelper namespaces
There are two syntax variants to import a ViewHelper namespace into a template.
In the following examples, blog is the namespace available within the Fluid template and
MyVendor\BlogExample\ViewHelpers is the PHP namespace to import into Fluid.
By default, the f namespace is predefined by Fluid. Depending on your setup,
additional global namespaces, defined directly via the
ViewHelperResolver, might
be available.
This is useful for various IDEs and HTML autocompletion. The <html>
element itself will not be rendered if the attribute
data-namespace-typo3-fluid="true" is specified.
The namespace is built using the fixed http://typo3.org/ns/ prefix followed
by the vendor name, package name, and the fixed ViewHelpers suffix.
Important
Do not use https://typo3.org/ (HTTPS instead of HTTP). Fluid would not be
able to detect this namespace to convert it to the PHP class name prefixes.
Remember: This is a unique XML namespace, it does not need to contain a valid URI.
Curly braces syntax
{namespace blog=MyVendor\BlogExample\ViewHelpers}
Copied!
Any line that uses the curly braces syntax results in a blank line. Multiple
statements can be on either one line or across multiple lines.
Fluid Syntax: Comments
If you want to completely skip parts of your template, you can make use of
the <f:comment> ViewHelper.
Changed in version Fluid 4.0
The content of the <f:comment> ViewHelper is removed
before parsing. It is no longer necessary to combine it with CDATA tags
to disable parsing.
<f:comment>
This will be ignored by the Fluid parser and will not appear in
the source code of the rendered template
</f:comment>
Copied!
Since the content of the <f:comment> ViewHelper is completely removed
before parsing, you can also use it to temporarily comment out invalid Fluid syntax while debugging:
<f:comment><x:someBrokenFluid></f:comment>
Copied!
Fluid (f:*)
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
ViewHelper to disable template compiling
Inserting this ViewHelper at any point in the template,
including inside conditions which do not get rendered,
will forcibly disable the caching/compiling of the full
template file to a PHP class.
Use this if for whatever reason your platform is unable
to create or load PHP classes (for example on read-only
file systems or when using an incompatible default cache
backend).
Passes through anything you place inside the ViewHelper,
so can safely be used as container tag, as self-closing
or with inline syntax - all with the same result.
Examples
Self-closing
<f:cache.disable />
Copied!
Inline mode
{f:cache.disable()}
Copied!
Container tag
<f:cache.disable>
Some output or Fluid code
</f:cache.disable>
Copied!
Additional output is also not compilable because of the ViewHelper
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
ViewHelper to force compiling to a static string
Used around chunks of template code where you want the
output of said template code to be compiled to a static
string (rather than a collection of compiled nodes, as
is the usual behavior).
The effect is that none of the child ViewHelpers or nodes
used inside this tag will be evaluated when rendering the
template once it is compiled. It will essentially replace
all logic inside the tag with a plain string output.
Works by turning the compile method into a method that
renders the child nodes and returns the resulting content
directly as a string variable.
You can use this with great effect to further optimise the
performance of your templates: in use cases where chunks of
template code depend on static variables (like thoese in
{settings} for example) and those variables never change,
and the template uses no other dynamic variables, forcing
the template to compile that chunk to a static string can
save a lot of operations when rendering the compiled template.
NB: NOT TO BE USED FOR CACHING ANYTHING OTHER THAN STRING-
COMPATIBLE OUTPUT!
USE WITH CARE! WILL PRESERVE EVERYTHING RENDERED, INCLUDING
POTENTIALLY SENSITIVE DATA CONTAINED IN OUTPUT!
Examples
Usage and effect
<f:if condition="{var}">Is always evaluated also when compiled</f:if>
<f:cache.static>
<f:if condition="{othervar}">
Will only be evaluated once and this output will be
cached as a static string with no logic attached.
The compiled template will not contain neither the
condition ViewHelperNodes or the variable accessor
that are used inside this node.
</f:if>
</f:cache.static>
Copied!
This is also evaluated when compiled (static node is closed):
<f:if condition="{var}">Also evaluated; is outside static node</f:if>
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
Modifies the case of an input string to upper- or lowercase or capitalization.
The default transformation will be uppercase as in mb_convert_case.
Possible modes are:
lower
Transforms the input string to lowercase
Example: "Hello World" -> "hello world"
upper
Transforms the input string to uppercase
Example: "Hello World" -> "HELLO WORLD"
capital
Transforms the first character of the input string to uppercase
Example: "hello world" -> "Hello world"
uncapital
Transforms the input string to its first letter lower-cased
Example: "Hello World" -> "hello World"
capitalWords
Transforms the input string to capitalize each word
Example: "hello world" -> "Hello World"
Note that the behavior will be the same as in the appropriate PHP function mb_convert_case;
especially regarding locale and multibyte behavior.
Examples
Default
<f:format.case>Some Text with miXed case</f:format.case>
The following arguments are available for the format.case ViewHelper:
mode
mode
Type
string
Default
'upper'
The case to apply, must be one of this' CASE_* constants. Defaults to uppercase application.
value
value
Type
string
The input value. If not given, the evaluated child nodes will be used.
Format.cdata ViewHelper <f:format.cdata>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
Outputs an argument/value without any escaping and wraps it with CDATA tags.
PAY SPECIAL ATTENTION TO SECURITY HERE (especially Cross Site Scripting),
as the output is NOT SANITIZED!
Examples
Child nodes
<f:format.cdata>{string}</f:format.cdata>
Copied!
Output:
<![CDATA[(Content of {string} without any conversion/escaping)]]>
Copied!
Value attribute
<f:format.cdata value="{string}" />
Copied!
Output:
<![CDATA[(Content of {string} without any conversion/escaping)]]>
Copied!
Inline notation
{string -> f:format.cdata()}
Copied!
Output:
<![CDATA[(Content of {string} without any conversion/escaping)]]>
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
Applies PHP htmlspecialchars() escaping to a value.
The following arguments are available for the format.htmlspecialchars ViewHelper:
doubleEncode
doubleEncode
Type
boolean
Default
true
If false, html entities will not be encoded
encoding
encoding
Type
string
Default
'UTF-8'
Encoding
keepQuotes
keepQuotes
Type
boolean
Default
false
If true quotes will not be replaced (ENT_NOQUOTES)
value
value
Type
string
Value to format
Format.json ViewHelper <f:format.json>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
The following arguments are available for the format.json ViewHelper:
forceObject
forceObject
Type
bool
Default
false
Outputs an JSON object rather than an array
value
value
Type
mixed
The incoming data to convert, or null if VH children should be used
Format.nl2br ViewHelper <f:format.nl2br>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
The following arguments are available for the format.nl2br ViewHelper:
value
value
Type
string
string to format
Format.number ViewHelper <f:format.number>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
The following arguments are available for the format.number ViewHelper:
decimalSeparator
decimalSeparator
Type
string
Default
'.'
The decimal point character
decimals
decimals
Type
int
Default
2
The number of digits after the decimal point
thousandsSeparator
thousandsSeparator
Type
string
Default
','
The character for grouping the thousand digits
Format.printf ViewHelper <f:format.printf>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
A ViewHelper for formatting values with printf. Either supply an array for
the arguments or a single value.
The following arguments are available for the format.printf ViewHelper:
arguments
arguments
Type
array
Default
array (
)
The arguments for vsprintf
value
value
Type
string
String to format
Format.raw ViewHelper <f:format.raw>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
Outputs an argument/value without any escaping. Is normally used to output
an ObjectAccessor which should not be escaped, but output as-is.
PAY SPECIAL ATTENTION TO SECURITY HERE (especially Cross Site Scripting),
as the output is NOT SANITIZED!
Examples
Child nodes
<f:format.raw>{string}</f:format.raw>
Copied!
Output:
(Content of ``{string}`` without any conversion/escaping)
Copied!
Value attribute
<f:format.raw value="{string}" />
Copied!
Output:
(Content of ``{string}`` without any conversion/escaping)
Copied!
Inline notation
{string -> f:format.raw()}
Copied!
Output:
(Content of ``{string}`` without any conversion/escaping)
The following arguments are available for the format.raw ViewHelper:
value
value
Type
mixed
The value to output
Format.stripTags ViewHelper <f:format.stripTags>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
The following arguments are available for the format.stripTags ViewHelper:
allowedTags
allowedTags
Type
string
Optional string of allowed tags as required by PHPs strip_tags() function
value
value
Type
string
string to format
Format.trim ViewHelper <f:format.trim>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
This ViewHelper strips whitespace (or other characters) from the beginning and end of a string.
Possible sides are:
both (default)
Strip whitespace (or other characters) from the beginning and end of a string
left or start
Strip whitespace (or other characters) from the beginning of a string
right or end
Strip whitespace (or other characters) from the end of a string
Examples
Defaults
#<f:format.trim> String to be trimmed. </f:format.trim>#
Copied!
#String to be trimmed.#
Copied!
Trim only one side
#<f:format.trim side="right"> String to be trimmed. </f:format.trim>#
Copied!
# String to be trimmed.#
Copied!
Trim special characters
#<f:format.trim characters=" St."> String to be trimmed. </f:format.trim>#
The following arguments are available for the format.trim ViewHelper:
characters
characters
Type
string
Optionally, the stripped characters can also be specified using the characters parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.
side
side
Type
string
Default
'both'
The side to apply, must be one of this' CASE_* constants. Defaults to both application.
value
value
Type
string
The string value to be trimmed. If not given, the evaluated child nodes will be used.
Format.urlencode ViewHelper <f:format.urlencode>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
The following arguments are available for the format.urlencode ViewHelper:
value
value
Type
string
string to format
Alias ViewHelper <f:alias>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
Declares new variables which are aliases of other variables.
Takes a "map"-Parameter which is an associative array which defines the shorthand mapping.
The variables are only declared inside the <f:alias>...</f:alias> tag. After the
closing tag, all declared variables are removed again.
Using this ViewHelper can be a sign of weak architecture. If you end up
using it extensively you might want to fine-tune your "view model" (the
data you assign to the view).
Examples
Single alias
<f:alias map="{x: 'foo'}">{x}</f:alias>
Copied!
Output:
foo
Copied!
Multiple mappings
<f:alias map="{x: foo.bar.baz, y: foo.bar.baz.name}">
{x.name} or {y}
</f:alias>
The following arguments are available for the alias ViewHelper:
map
map
Type
array
Required
1
Array that specifies which variables should be mapped to which alias
Argument ViewHelper <f:argument>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
f:argument allows to define requirements and type constraints to variables that
are provided to templates and partials. This can be very helpful to document how
a template or partial is supposed to be used and which input variables are required.
These requirements are enforced during rendering of the template or partial:
If an argument is defined with this ViewHelper which isn't marked as optional,
an exception will be thrown if that variable isn't present during rendering.
If a variable doesn't match the specified type and can't be converted automatically,
an exception will be thrown as well.
Note that f:argument ViewHelpers must be used at the root level of the
template, and can't be nested into other ViewHelpers. Also, the usage of variables
in any of its arguments is not possible (e. g. you can't define an argument name
by using a variable).
Rendering of specific sections will not validate argument constraints. They
will only be evaluated if the template or partial is rendered directly.
<!-- All arguments supplied --><f:renderpartial="MyPartial"arguments="{title: 'My title', tags: {0: 'tag1', 1: 'tag2'}, user: 'me'}" /><!-- "user" will fall back to default value --><f:renderpartial="MyPartial"arguments="{title: 'My title', tags: {0: 'tag1', 1: 'tag2'}}" /><!-- "tags" will be "null", "user" will fall back to default value --><f:renderpartial="MyPartial"arguments="{title: 'My title'}" />
Copied!
The following render calls will result in an exception:
<!-- required "title" has not been supplied --><f:renderpartial="MyPartial" /><!-- "user" has been supplied as array, not as string --><f:renderpartial="MyPartial"arguments="{title: 'My title', user: {firstName: 'Jane', lastName: 'Doe'}}" />
Copied!
Union Types
Changed in version Fluid 5.0
Union types are supported for component arguments.
An argument can allow multiple multiple types. In that case, the component's implementation
needs to make sure that all possible variants are considered. This should be used sparingly
since it can complicate the component's implementation code considerably.
The following arguments are available for the argument ViewHelper:
default
default
Type
mixed
default value for optional argument
description
description
Type
string
description of the template argument
name
name
Type
string
Required
1
name of the template argument
optional
optional
Type
boolean
Default
false
true if the defined argument should be optional
type
type
Type
string
Required
1
type of the template argument
Case ViewHelper <f:case>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
Case ViewHelper that is only usable within the f:switch ViewHelper.
The following arguments are available for the ceil ViewHelper:
value
value
Type
float
The number that should be rounded up
Comment ViewHelper <f:comment>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
This ViewHelper prevents rendering of any content inside the tag.
Contents of the comment will not be parsed thus it can be used to
comment out invalid Fluid syntax or non-existent ViewHelpers during
development.
Using this ViewHelper won't have a notable effect on performance,
especially once the template is parsed. However, it can lead to reduced
readability. You can use layouts and partials to split a large template
into smaller parts. Using self-descriptive names for the partials can
make comments redundant.
Examples
Commenting out fluid code
Before
<f:comment>
This is completely hidden.
<f:debug>This does not get rendered</f:debug>
</f:comment>
After
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
The following arguments are available for the constant ViewHelper:
name
name
Type
string
String representation of a PHP constant or enum
Contains ViewHelper <f:contains>
The ContainsViewHelper checks if a provided string or array contains
the specified value. Depending on the input, this mimicks PHP's
in_array() or str_contains().
The following arguments are available for the contains ViewHelper:
else
else
Type
mixed
Value to be returned if the condition if not met.
subject
subject
Type
mixed
Required
1
The string or array that might contain the value (haystack)
then
then
Type
mixed
Value to be returned if the condition if met.
value
value
Type
mixed
Required
1
The value to check for (needle)
Count ViewHelper <f:count>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
This ViewHelper counts elements of the specified array or countable object.
Examples
Count array elements
<f:count subject="{0:1, 1:2, 2:3, 3:4}" />
Copied!
Output:
4
Copied!
inline notation
{objects -> f:count()}
Copied!
Output:
10 (depending on the number of items in ``{objects}``)
The following arguments are available for the count ViewHelper:
subject
subject
Type
array
Countable subject, array or \Countable
Cycle ViewHelper <f:cycle>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
This ViewHelper cycles through the specified values.
This can be often used to specify CSS classes for example.
To achieve the "zebra class" effect in a loop you can also use the
"iteration" argument of the for ViewHelper.
Examples
These examples could also be achieved using the "iteration" argument
of the ForViewHelper.
The following arguments are available for the cycle ViewHelper:
as
as
Type
string
Required
1
The name of the iteration variable
values
values
Type
array
The array or object implementing \ArrayAccess (for example \SplObjectStorage) to iterated over
Debug ViewHelper <f:debug>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
This ViewHelper is only meant to be used during development.
Examples
Inline notation and custom title
{object -> f:debug(title: 'Custom title')}
Copied!
Output:
all properties of {object} nicely highlighted (with custom title)
The following arguments are available for the debug ViewHelper:
html
html
Type
boolean
Default
false
Render HTML. If false, output is indented plaintext
levels
levels
Type
integer
Default
5
Levels to render when rendering nested objects/arrays
typeOnly
typeOnly
Type
boolean
Default
false
If true, debugs only the type of variables
DefaultCase ViewHelper <f:defaultCase>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
A ViewHelper which specifies the "default" case when used within the f:switch ViewHelper.
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
Else-Branch of a condition. Only has an effect inside of f:if.
See the f:if ViewHelper for documentation.
Examples
Output content if condition is not met
<f:if condition="{someCondition}">
<f:else>
condition was not true
</f:else>
</f:if>
Copied!
Output:
Everything inside the "else" tag is displayed if the condition evaluates to false.
Otherwise, nothing is outputted in this example.
The following arguments are available for the else ViewHelper:
if
if
Type
boolean
Condition expression conforming to Fluid boolean rules
EndsWith ViewHelper <f:endsWith>
EndsWith ViewHelper checks if the subject string ends with a specified string.
This ViewHelper implements an if/else condition.
Examples
Render the body if "myString" ends with "World!"
<f:variable name="myString" value="Hello, World!" />
<f:endsWith search="Hello" subject="{myString}">This will be rendered if variable "myString" ends with "World!"</f:endsWith>
Copied!
Output:
This will be rendered if variable "myString" ends with "World!"
The following arguments are available for the endsWith ViewHelper:
else
else
Type
mixed
Value to be returned if the condition if not met.
search
search
Type
string
Required
1
String to search in subject at the beginning
subject
subject
Type
string
Required
1
String to search in
then
then
Type
mixed
Value to be returned if the condition if met.
First ViewHelper <f:first>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
The FirstViewHelper returns the first item of an array.
The following arguments are available for the first ViewHelper:
value
value
Type
array
Flatten ViewHelper <f:flatten>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
The FlattenViewHelper flattens a multi-dimensional array into a
single-dimensional array.
The following arguments are available for the floor ViewHelper:
value
value
Type
float
The number that should be rounded down
For ViewHelper <f:for>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
Loop ViewHelper which can be used to iterate over arrays.
Implements what a basic PHP foreach() does.
The following arguments are available for the for ViewHelper:
as
as
Type
string
Required
1
The name of the iteration variable
each
each
Type
array
Required
1
The array or \SplObjectStorage to iterated over
iteration
iteration
Type
string
The name of the variable to store iteration information (index, cycle, total, isFirst, isLast, isEven, isOdd)
key
key
Type
string
Variable to assign array key to
reverse
reverse
Type
boolean
Default
false
If true, iterates in reverse
Fragment ViewHelper <f:fragment>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
f:fragment is the counterpart of the <f:slot> ViewHelper.
It allows to provide multiple HTML fragments to a component, which defines
the matching named slots. f:fragment is used directly inside a component
tag, nesting into other ViewHelpers is not possible.
<my:textMediatitle="My title"><f:fragmentname="media"><imgsrc="path/to/image.jpg"alt="..." /></f:fragment><f:fragmentname="content"><p>My first paragraph</p><p>My second paragraph</p></f:fragment></my:textMedia>
Copied!
it will result in the following output:
<divclass="textMediaComponent"><h2>My title</h2><divclass="textMediaComponent__media"><imgsrc="path/to/image.jpg"alt="..." /></div><divclass="textMediaComponent__content"><p>My first paragraph</p><p>My second paragraph</p></div></div>
The following arguments are available for the fragment ViewHelper:
name
name
Type
string
Default
'default'
Name of the slot that should be filled
GroupedFor ViewHelper <f:groupedFor>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
Grouped loop ViewHelper.
Loops through the specified values.
The groupBy argument also supports property paths.
Using this ViewHelper can be a sign of weak architecture. If you end up
using it extensively you might want to fine-tune your "view model" (the
data you assign to the view).
The following arguments are available for the groupedFor ViewHelper:
as
as
Type
string
Required
1
The name of the iteration variable
each
each
Type
array
Required
1
The array or \SplObjectStorage to iterated over
groupBy
groupBy
Type
string
Required
1
Group by this property
groupKey
groupKey
Type
string
Default
'groupKey'
The name of the variable to store the current group
If ViewHelper <f:if>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
This ViewHelper implements an if/else condition.
Fluid Boolean Rules / Conditions:
A condition is evaluated as a boolean value, so you can use any
boolean argument, like a variable.
Alternatively, you can use a full boolean expression.
The entered expression is evaluated as a PHP expression. You can
combine multiple expressions via && (logical AND) and
|| (logical OR).
An expression can also be prepended with the ! ("not") character,
which will negate that expression.
Have a look into the Fluid section of the "TYPO3 Explained" Documentation
for more details about complex conditions.
Boolean expressions have the following form:
is true variant: {variable}:
<f:if condition="{foo}">
Will be shown if foo is truthy.
</f:if>
Copied!
or is false variant: !{variable}:
<f:if condition="!{foo}">
Will be shown if foo is falsy.
</f:if>
Copied!
or comparisons with expressions:
XX Comparator YY
Copied!
Comparator is one of: ==, !=, <, <=, >, >= and %
The % operator (modulo) converts the result of the operation to
boolean.
XX and YY can be one of:
Number
String
Object Accessor (object.property)
Array
a ViewHelper
<f:if condition="{rank} > 100">
Will be shown if rank is > 100
</f:if>
<f:if condition="{rank} % 2">
Will be shown if rank % 2 != 0.
</f:if>
<f:if condition="{rank} == {k:bar()}">
Checks if rank is equal to the result of the ViewHelper "k:bar"
</f:if>
<f:if condition="{object.property} == 'stringToCompare'">
Will result in trueif {object.property}'s represented value
equals 'stringToCompare'.
</f:if>
Copied!
Examples
Basic usage
<f:if condition="somecondition">
This is being shown in case the condition matches
</f:if>
Copied!
Output:
Everything inside the <f:if> tag is being displayed if the condition evaluates to true.
Copied!
If / then / else
<f:if condition="somecondition">
<f:then>
This is being shown in case the condition matches.
</f:then>
<f:else>
This is being displayed in case the condition evaluates to false.
</f:else>
</f:if>
Copied!
Output:
Everything inside the "then" tag is displayed if the condition evaluates to true.
Otherwise, everything inside the "else" tag is displayed.
Copied!
Inline notation
{f:if(condition: someCondition, then: 'condition is met', else: 'condition is not met')}
Copied!
Output:
The value of the "then" attribute is displayed if the condition evaluates to true.
Otherwise, everything the value of the "else" attribute is displayed.
Copied!
Combining multiple conditions
<f:if condition="{user.rank} > 100 && {user.type} == 'contributor'">
<f:then>
This is being shown in case both conditions match.
</f:then>
<f:elseif="{user.rank} > 200 && ({user.type} == 'contributor' || {user.type} == 'developer')">
This is being displayed in case the first block of the condition evaluates to trueand any condition in
the second condition block evaluates to true.
</f:else>
<f:else>
This is being displayed when none of the above conditions evaluated to true.
</f:else>
</f:if>
Copied!
Output:
Depending on which expression evaluated to true, that value is displayed.
If no expression matched, the contents inside the final"else" tag are displayed.
The following arguments are available for the if ViewHelper:
condition
condition
Type
boolean
Default
false
Condition expression conforming to Fluid boolean rules
else
else
Type
mixed
Value to be returned if the condition if not met.
then
then
Type
mixed
Value to be returned if the condition if met.
Inline ViewHelper <f:inline>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
Inline Fluid rendering ViewHelper
Renders Fluid code stored in a variable, which you normally would
have to render before assigning it to the view. Instead you can
do the following (note, extremely simplified use case):
$view->assign('variable', 'value of my variable');
$view->assign('code', 'My variable: {variable}');
Copied!
And in the template:
{code -> f:inline()}
Copied!
Which outputs:
My variable: value of my variable
Copied!
You can use this to pass smaller and dynamic pieces of Fluid code
to templates, as an alternative to creating new partial templates.
The following arguments are available for the inline ViewHelper:
code
code
Type
string
Fluid code to be rendered as if it were part of the template rendering it. Can be passed as inline argument or tag content
Join ViewHelper <f:join>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
The JoinViewHelper combines elements from an array into a single string.
You can specify both a general separator and a special one for the last
element, which serves as the delimiter between the elements.
The following arguments are available for the join ViewHelper:
separator
separator
Type
string
Default
''
The separator
separatorLast
separatorLast
Type
string
The separator for the last pair.
value
value
Type
array
An array
Last ViewHelper <f:last>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
The LastViewHelper returns the last item of an array.
The following arguments are available for the last ViewHelper:
value
value
Type
array
Layout ViewHelper <f:layout>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
With this ViewHelper, you can select a layout to be used for the current template.
Attention
Prevously, it was possible to set the layout of a template with the special
variable layoutName. This is no longer possible with Fluid 5.
The following arguments are available for the min ViewHelper:
value
value
Type
array
An array
Or ViewHelper <f:or>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
Or ViewHelper
If content is null use alternative text.
Usage of f:or
{f:variable(name:'fallback',value:'this is not the variable you\'re looking for')}
{undefinedVariable -> f:or(alternative:fallback)}
Copied!
Usage of ternary operator
In some cases (e.g. when you want to check for empty instead of null)
it might be more handy to use a ternary operator instead of f:or
The following arguments are available for the range ViewHelper:
end
end
Type
integer
Required
1
Last possible value of the sequence.
start
start
Type
integer
Required
1
First value of the sequence.
step
step
Type
integer
Default
1
indicates by how much the produced sequence is progressed between values of the sequence.
Render ViewHelper <f:render>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
A ViewHelper to render a section, a partial, a specified section in a partial
or a delegate ParsedTemplateInterface implementation.
This will output whichever output was generated by calling My\Special\ParsedTemplateImplementation->render()
with cloned RenderingContextInterface $renderingContext as only argument and content of arguments
assigned in VariableProvider of cloned context. Supports all other input arguments including
recursive rendering, contentAs argument, default value etc.
Note that while ParsedTemplateInterface supports returning a Layout name, this Layout will not
be respected when rendering using this method. Only the render() method will be called!
The following arguments are available for the render ViewHelper:
arguments
arguments
Type
array
Default
array (
)
Array of variables to be transferred. Use {_all} for all variables
contentAs
contentAs
Type
string
If used, renders the child content and adds it as a template variable with this name for use in the partial/section
default
default
Type
mixed
Value (usually string) to be displayed if the section or partial does not exist
delegate
delegate
Type
string
Optional PHP class name of a permanent, included-in-app ParsedTemplateInterface implementation to override partial/section
optional
optional
Type
boolean
Default
false
If true, considers the *section* optional. Partial never is.
partial
partial
Type
string
Partial to render, with or without section
section
section
Type
string
Section to render - combine with partial to render section in partial
Replace ViewHelper <f:replace>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
The ReplaceViewHelper replaces one or multiple strings with other
strings. This ViewHelper mimicks PHP's str_replace() function.
However, it's also possible to provide replace pairs as associative array
via the "replace" argument.
The following arguments are available for the round ViewHelper:
precision
precision
Type
int
Default
2
Rounding precision
roundingMode
roundingMode
Type
string
Default
'HalfAwayFromZero'
Rounding mode
value
value
Type
float
The number that should be rounded
Section ViewHelper <f:section>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
A ViewHelper to declare sections in templates for later use with e.g. the f:render ViewHelper.
Examples
Rendering sections
<f:section name="someSection">This is a section. {foo}</f:section>
<f:render section="someSection" arguments="{foo: someVariable}" />
Copied!
Output:
the content of the section "someSection". The content of the variable {someVariable} will be available in the partial as {foo}
The following arguments are available for the section ViewHelper:
name
name
Type
string
Required
1
Name of the section
Shuffle ViewHelper <f:shuffle>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
The ShuffleViewHelper shuffles elements from an array.
This ViewHelper uses PHP's shuffle() function.
The following arguments are available for the shuffle ViewHelper:
value
value
Type
array
An array
Slot ViewHelper <f:slot>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
f:slot allows a template that is called as a component to access and render
the child content of the calling component tag. This makes nesting of components
possible.
Most importantly, the f:slot ViewHelper makes sure that the right level of
HTML escaping happens automatically, in line with the escaping in other parts of
Fluid: If HTML is used directly, it is not escaped. However, if a variable is
used within the child content that contains a HTML string, that HTML is escaped
because it might be from an unknown source.
In combination with the <f:fragment> ViewHelper,
multiple slots can be used in one component.
If a slot is defined, this ViewHelper will always attempt to return a string,
regardless of the original type of the content. If a slot is not defined, the
ViewHelper will return null.
<my:texttitle="My title"><p>My first paragraph</p><p>My second paragraph</p></my:text>
Copied!
it will result in the following output:
<divclass="textComponent"><h2>My title</h2><divclass="textComponent__content"><p>My first paragraph</p><p>My second paragraph</p></div></div>
Copied!
Escaping Example
If the same component is called like this:
<f:variablename="htmlString"><p>My first paragraph</p><p>My second paragraph</p></f:variable><my:texttitle="My title">{htmlString}</my:text>
Copied!
it would result in escaped HTML:
<divclass="textComponent"><h2>My title</h2><divclass="textComponent__content"><p>My first paragraph</p><p>My second paragraph</p></div></div>
Copied!
If you want to avoid escaping in this use case, you need to use f:format.raw on
the variable when it's passed to the component. Please be aware that depending on
the source of the input, this might have security implications!
Component Nesting Example
Nesting of multiple components is possible. The following template Paragraphs.html:
<p>My first paragraph</p><p>My second paragraph</p>
Copied!
can be called as a component and nested into the text component described above:
<my:textMediatitle="My title"><f:fragmentname="media"><imgsrc="path/to/image.jpg"alt="..." /></f:fragment><f:fragmentname="content"><p>My first paragraph</p><p>My second paragraph</p></f:fragment></my:textMedia>
Copied!
it will result in the following output:
<divclass="textMediaComponent"><h2>My title</h2><divclass="textMediaComponent__media"><imgsrc="path/to/image.jpg"alt="..." /></div><divclass="textMediaComponent__content"><p>My first paragraph</p><p>My second paragraph</p></div></div>
The following arguments are available for the slot ViewHelper:
name
name
Type
string
Default
'default'
Name of the slot, can be omitted for default slot
Spaceless ViewHelper <f:spaceless>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
Space Removal ViewHelper
Removes redundant spaces between HTML tags while
preserving the whitespace that may be inside HTML
tags. Trims the final result before output.
Heavily inspired by Twig's corresponding node type.
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
The SplitViewHelper splits a string by the specified separator, which
results in an array. The number of values in the resulting array can
be limited with the limit parameter, which results in an array where
the last item contains the remaining unsplit string.
This ViewHelper mimicks PHP's explode() function.
The following examples store the result in a variable because an array cannot
be outputted directly in a template.
The following arguments are available for the split ViewHelper:
limit
limit
Type
int
Default
9223372036854775807
If limit is positive, a maximum of $limit items will be returned. If limit is negative, all items except for the last $limit items will be returned. 0 will be treated as 1.
separator
separator
Type
string
Required
1
Separator string to explode with
value
value
Type
string
The string to explode
StartsWith ViewHelper <f:startsWith>
StartsWith ViewHelper checks if the subject string starts with a specified string.
This ViewHelper implements an if/else condition.
Examples
Render the body if "myString" starts with "Hello"
<f:variable name="myString" value="Hello, World!" />
<f:startsWith search="Hello" subject="{myString}">This will be rendered if variable "myString" starts with "Hello"</f:startsWith>
Copied!
Output:
This will be rendered if variable "myString" starts with "Hello"
The following arguments are available for the startsWith ViewHelper:
else
else
Type
mixed
Value to be returned if the condition if not met.
search
search
Type
string
Required
1
String to search in subject at the beginning
subject
subject
Type
string
Required
1
String to search in
then
then
Type
mixed
Value to be returned if the condition if met.
Switch ViewHelper <f:switch>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
Switch ViewHelper which can be used to render content depending on a value or expression.
Implements what a basic PHP switch() does.
An optional default case can be specified which is rendered if none of the
case conditions matches.
Using this ViewHelper can be a sign of weak architecture. If you end up using it extensively
you might want to consider restructuring your controllers/actions and/or use partials and sections.
E.g. the above example could be achieved with <f:render partial="title.{person.gender}" />
and the partials "title.male.html", "title.female.html", ...
Depending on the scenario this can be easier to extend and possibly contains less duplication.
The following arguments are available for the switch ViewHelper:
expression
expression
Type
mixed
Required
1
Expression to switch
Then ViewHelper <f:then>
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
f:then only has an effect inside of f:if. See the f:if ViewHelper for documentation.
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.
Variable assigning ViewHelper
Assigns one template variable which will exist also
after the ViewHelper is done rendering, i.e. adds
template variables.
If you require a variable assignment which does not
exist in the template after a piece of Fluid code
is rendered, consider using f:alias ViewHelper instead.
The following arguments are available for the variable ViewHelper:
name
name
Type
string
Required
1
Name of variable to create
value
value
Type
mixed
Value to assign. If not in arguments then taken from tag content
ViewHelper XSD Schema Files
Fluid supports autocompletion of the special Fluid tags via the use of an XSD
schema - a standard feature of the XML toolchain which allows defining required
attributes, expected attribute types and more. Some IDEs support the mapping of
such XSD schemas to XML namespace URLs (xmlns="...") which you can include in
Fluid templates.
Fluid includes the necessary CLI command to generate such schema files for all
available ViewHelpers within your project:
./vendor/bin/fluid schema
Copied!
If no other parameter is defined, the CLI command will create a schema file for
each available namespace in the current directory, for example:
You can specify a different destination directory by providing the --destination
argument. If the directory doesn't exist, it will be created:
./vendor/bin/fluid schema --destination schemas/
Copied!
Extending Fluid
Creating ViewHelpers
Learn how to extend Fluid by creating custom ViewHelpers
Creating ExpressionNodes
Learn how to extend Fluid by creating custom expression syntax
Providing External Components
Learn how to integrate external component libraries into Fluid
Creating ViewHelpers
Creating a ViewHelper is extremely simple. First, make sure you read the
chapter about using ViewHelpers so you know where
ViewHelper class files are expected to be placed in your own package and that
you understand how/why you would require a custom ViewHelper.
Let's create an example ViewHelper which will accept exactly two arguments, both
arrays, and use those arrays to create a new array using array_combine which
takes one argument with keys and another of the same size with values. We would
like this new ViewHelper to be usable in inline syntax - for example as value of
the each argument on f:for to iterate the combined array. And finally, we
would like to be able to specify the "values" array also in the special inline
syntax for tag content:
To enable this usage we must then create a ViewHelper class:
<?phpnamespaceVendor\Package\ViewHelpers;
useTYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
/**
* This ViewHelper takes two arrays and returns
* the `array_combine`d result.
*/classCombineViewHelperextendsAbstractViewHelper{
publicfunctioninitializeArguments(): void{
$this->registerArgument('values', 'array', 'Values to use in array_combine');
$this->registerArgument('keys', 'array', 'Keys to use in array_combine', true);
}
/**
* Combines two arrays using one for keys and
* the other for values. If values are not provided
* in argument it can be provided as tag content.
*/publicfunctionrender(): array{
$values = $this->arguments['values'];
$keys = $this->arguments['keys'];
if ($values === null) {
$values = $this->renderChildren();
}
return array_combine($keys, $values);
}
}
Copied!
And that's all this class requires to work in the described way.
Note that in this example the ViewHelper's render() method returns an array
which means you can't use it in tag mode:
<htmlxmlns:mypkg="Vendor\Package\ViewHelpers"><!-- BAD USAGE. Will output string value "Array" --><mypkg:combinekeys="{myKeysArray}">{myValuesArray}</mypkg:combine></html>
Copied!
Naturally this implies that any ViewHelper which returns a string compatible
value (including numbers and objects which have a __toString() method) can be
used in tag mode or inline mode - whereas ViewHelpers that return other data
types normally only make sense to use in inline mode; as values of other
ViewHelpers' attributes that require the returned value type. For example,
ViewHelpers which format output should always return a string (examples of such
ViewHelpers might be ones that implement strip_tags, nl2br or other
string-manipulating PHP functions). And data ViewHelpers may return any type,
but must be used a bit more carefully.
In other words: be careful what data types your ViewHelper returns.
Non-string-compatible values may cause problems if you use the ViewHelper in
ways that were not intended. Like in PHP, data types must either match or be
mutually compatible.
Invoking other ViewHelpers
Warning
In general, it is advised to keep ViewHelpers small and to extract more
complicated code into its own service class.
In some cases, it might be helpful or necessary to call a ViewHelper from
another ViewHelper, for example to reuse its functionality. This can be
achieved by using the ViewHelperInvoker:
In addition to the API of AbstractViewHelper, ViewHelpers can hook into
the parsing process by implementing ViewHelperNodeInitializedEventInterface.
The interface requires the ViewHelper class to implement an additional static method
nodeInitializedEvent(), which is called during the initial parsing of a
template that uses the ViewHelper. In the method, you receive the current
parsing state of the template as well as relevant information about the
ViewHelper call, which allows for additional syntax validation and special
low-level processing.
The following example ensures that the ViewHelper can only be used on the first
nesting level and thus cannot be nested into other ViewHelpers:
useTYPO3Fluid\Fluid\Core\Parser\ParsingState;
useTYPO3Fluid\Fluid\Core\Parser\SyntaxTree\ViewHelperNode;
useTYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
useTYPO3Fluid\Fluid\Core\ViewHelper\ViewHelperNodeInitializedEventInterface;
finalclassFooViewHelperextendsAbstractViewHelperimplementsViewHelperNodeInitializedEventInterface{
publicstaticfunctionnodeInitializedEvent(ViewHelperNode $node, array $arguments, ParsingState $parsingState): void{
if ($parsingState->hasNodeTypeInStack(ViewHelperNode::class)) {
thrownew \TYPO3Fluid\Fluid\Core\Parser\Exception(sprintf(
'FooViewHelper needs to be defined at the root level of the template.',
), 1750671904);
}
}
}
Copied!
This event is used by Fluid internally in the SectionViewHelper,
the LayoutViewHelper and the ArgumentViewHelper.
Deprecated since version 4.2
NodeInitialized event replaces the old AbstractViewHelper::postParseEvent() method,
which will no longer work with Fluid 5.
Creating ExpressionNodes
The ExpressionNode concept is the most profound way you can manipulate the
Fluid language itself, adding to it new syntax options that can be used inside
the shorthand {...} syntax. Normally you are confined to using ViewHelpers
when you want such special processing in your templates - but using
ExpressionNodes allows you to add these processings as actual parts of the
templating language itself; avoiding the need to include a ViewHelper namespace.
Fluid itself provides the following types of ExpressionNodes:
MathExpressionNode which scans for and evaluates simple mathematical
expressions like {variable + 1}.
TernaryExpressionNode which implements a ternary condition in Fluid syntax
like {ifsomething ? thenoutputthis : elsethis}
CastingExpressionNode which casts variables to a certain type, e.g.
{suspectType as integer}, {myInteger as boolean}.
An ExpressionNode basically consists of one an expression matching pattern
(regex), one non-static method to evaluate the expression
public function evaluate(RenderingContextInterface $renderingContext)
and a mirror of this function which can be called statically:
public static evaluteExpression(RenderingContextInterface $renderingContext, $expression).
The non-static method should then simply delegate to the static method and use
the expression stored in $this->expression as second parameter for the static
method call.
ExpressionNodes automatically support compilation and will generate compiled
code which stores the expression and calls the static evaluateExpression()
method with the rendering context and the stored expression.
You should create your own ExpressionNodes if:
You want a custom syntax in your Fluid templates (theoretical example:
casting variables using {(integer)variablename}).
You want to replace either of the above mentioned ExpressionNodes with ones
using the same, or an expanded version of their regular expression patterns
to further extend the strings they capture and process.
Implementation
An ExpressionNode is always one PHP class. Where you place it is
completely up to you - but to have the class actually be detected and used by
Fluid, it needs to be added to the rendering context by calling setExpressionNodeTypes().
In Fluid's default RenderingContext, the following code is responsible for
returning expression node class names:
/**
* List of class names implementing ExpressionNodeInterface
* which will be consulted when an expression does not match
* any built-in parser expression types.
*
* @var string
*/protected $expressionNodeTypes = [
'TYPO3Fluid\\Fluid\\Core\\Parser\\SyntaxTree\\Expression\\CastingExpressionNode',
'TYPO3Fluid\\Fluid\\Core\\Parser\\SyntaxTree\\Expression\\MathExpressionNode',
'TYPO3Fluid\\Fluid\\Core\\Parser\\SyntaxTree\\Expression\\TernaryExpressionNode',
];
/**
* @return string
*/publicfunctiongetExpressionNodeTypes(){
return$this->expressionNodeTypes;
}
Copied!
You may or may not want the listed expression nodes included, but if you change
the available expression types you should of course document this difference
about your implementation.
The following class is the math ExpressionNode from Fluid itself
which detects the {a + 1} and other simple mathematical operations.
To get this behavior, we need a (relatively
simple) regular expression and one method to evaluate the expression while being
aware of the rendering context (which stores all variables, controller name,
action name etc).
<?phpnamespaceTYPO3Fluid\Fluid\Core\Parser\SyntaxTree\Expression;
useTYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
classMathExpressionNodeextendsAbstractExpressionNode{
/**
* Pattern which detects the mathematical expressions with either
* object accessor expressions or numbers on left and right hand
* side of a mathematical operator inside curly braces, e.g.:
*
* {variable * 10}, {100 / variable}, {variable + variable2} etc.
*/publicstatic string $detectionExpression = '/
(
{ # Start of shorthand syntax
\s* # Allow whitespace before expression
(?: # Math expression is composed of...
[_a-zA-Z0-9\.]+(?:[\s]*[*+\^\/\%\-]{1}[\s]*[_a-zA-Z0-9\.]+)+ # Various math expressions left and right sides with any spaces
|(?R) # Other expressions inside
)+
\s* # Allow whitespace after expression
} # End of shorthand syntax
)/x';
publicstaticfunctionevaluateExpression(RenderingContextInterface $renderingContext, string $expression, array $matches): int|float{
// Split the expression on all recognized operators
$matches = [];
preg_match_all('/([+\-*\^\/\%]|[_a-zA-Z0-9\.]+)/s', $expression, $matches);
$matches[0] = array_map('trim', $matches[0]);
// Like the BooleanNode, we dumb down the processing logic to not apply// any special precedence on the priority of operators. We simply process// them in order.
$result = array_shift($matches[0]);
$result = static::getTemplateVariableOrValueItself($result, $renderingContext);
$result = ($result == (int)$result) ? (int)$result : (float)$result;
$operator = null;
$operators = ['*', '^', '-', '+', '/', '%'];
foreach ($matches[0] as $part) {
if (in_array($part, $operators)) {
$operator = $part;
} else {
$part = static::getTemplateVariableOrValueItself($part, $renderingContext);
$part = ($part == (int)$part) ? (int)$part : (float)$part;
$result = self::evaluateOperation($result, $operator, $part);
}
}
return $result;
}
// ...
}
Copied!
Taking from this example class the following are the rules you must observe:
You must either subclass the AbstractExpressionNode class or implement the
ExpressionNodeInterface (subclassing the right class will automatically
implement the right interface).
You must provide the class with an exact property called
public static $detectionExpression which contains a string that is a perl
regular expression which will result in at least one match when run against
expressions you type in Fluid. It is vital that the property be both
static and public and have the right name - it is accessed without
instantiating the class.
The class must have a public static function evaluateExpression taking
exactly the arguments above - nothing more, nothing less. The method must be
able to work in a static context (it is called this way once templates have
been compiled).
The evaluateExpression method may return any value type you desire, but
like ViewHelpers, returning a non-string-compatible value implies that you
should be careful about how you then use the expression; attempting to render
a non-string-compatible value as a string may cause PHP warnings.
Providing External Components
New in version Fluid 4.3
Fluid supports components that are defined as Fluid templates
out-of-the-box. However, it is also possible to integrate external component
libraries into your Fluid-based project. This makes it possible to bridge
the gap between Fluid and other templating engines, such as Twig or Mustache.
Note
There are no official integrations of Fluid with other templating engines.
This page merely demonstrates how existing Fluid APIs can be used
to achieve this.
Architecture Overview
Fluid's component features are based on several classes and interfaces. Some
are meant to be extended/implemented, others merely exist for internal
purposes and are annotated as @internal in the PHPDoc header.
The ComponentDefinitionProviderInterface, together with
ComponentRendererInterface, are the primary interfaces that can
be used (together with a ViewHelperResolver delegate)
to "teach" Fluid how to interact with components. The definition provider
returns instances of ComponentDefinition, which is an immutable DTO.
The ComponentAdapter is an adapter class that translates between the
ViewHelper API and the described components API. It is used as default
ViewHelper implementation for all components during parse-time and will never
be used once a template is cached. It is marked @internal and is not
intended to be extended/replaced.
The ComponentTemplateResolverInterface is an internal interface that is
related to Fluid's own component implementation. Same goes for
ComponentRenderer, which renders Fluid-based component templates.
AbstractComponentCollection is the base implementation for Fluid-based
components, which are documented in a separate chapter about
Components.
Custom ComponentRenderer
The ComponentRendererInterface specifies how a component should be rendered.
This is the place where e. g. an external templating engine would be initiated
to render a specific template:
The $parentRenderingContext can be used to extract additional information from
the parent Fluid template that should be passed to the component, such as a Request
object.
Custom ComponentDefinitionProvider
The ComponentDefinitionProviderInterface provides Fluid with all necessary
information to resolve, validate and render external components. Depending
on the available component metadata, the Fluid parser is even able to pre-validate
the supplied component parameters (defined and required arguments, booleans). However, it is
also possible to provide a "non-strict" implementation where any argument can be supplied
to the external components. The interface must always be used in combination with
ViewHelperResolverDelegateInterface.
Fluid provides a standard implementation which works great on simple MVC
frameworks and as standalone rendering engine. However, the standard
implementation may lack certain features needed by the product into which you
are integrating Fluid.
To make sure you are able to override key behaviors of Fluid the package
will delegate much of the resolving, instantiation, argument mapping and
rendering of ViewHelpers to special classes which can be both manipulated and
overridden by the user. These special classes and their use cases are:
A fairly standard View implementation. The default object expects
TemplatePaths as constructor argument and has a handful of utility methods
like $view->assign('variablename', 'value');. Custom View types can be
implemented by subclassing the default class - but in order to avoid
problems, make sure you also call the original class' constructor method.
Creating a custom View allows you to change just a few aspects, mainly about
composition: which implementations of TemplatePaths the View requires, if it
needs a custom ViewHelperResolver,
if it must have some default variables, if it should have a default cache, etc.
Deprecated since version 4.4
Prevously, it was possible to set the layout of a template with the special
variable layoutName. This will no longer work with Fluid 5. Please use the
<f:layout> ViewHelper
instead.
TemplatePaths
In the default TemplatePaths object included with Fluid we provide a
set of conventions for resolving the template files that go into rendering a
Fluid template - the templates themselves, plus partials and layouts.
You should use the default TemplatePaths object if:
You are able to place your template files in folders that match the
Fluid conventions, including the convention of subfolders named the
same as your controllers.
You are able to provide the template paths that get used as an array with
which TemplatePaths can be initialized.
Or you are able to individually set each group of paths.
You are able to rely on standard format handling (format simply being the
file extension of template files).
And you should replace the TemplatePaths with your own subclass if:
You answered no to any of the above.
You want to be able to deliver template content before parsing, from other
sources than files.
You want the resolving of template files for controller actions to happen in
a different way.
You want to create other (caching-) identifiers for your partials, layouts
and templates than defaults.
Whether you use your own class or the default, the TemplatePaths instance
must be provided as first argument for the View.
RenderingContext
The rendering context is the state object in Fluid's rendering process.
By default, it contains references to all other objects that are relevant
in the rendering process, such as the TemplateParser, the TemplateCompiler,
a StandardVariableProvider or the TemplatePaths mentioned above.
It also contains information about the current template context, somewhat
confusingly stored in controllerName and controllerAction due to the
MVC origins of Fluid.
Since Fluid 2.14, it is also possible to add arbitrary data to the rendering
context, which obsoletes most cases where you would have to override the
rendering context implementation in Fluid integrations:
$myCustomState = new \Vendor\Package\MyClass::class();
$view->getRenderingContext()->setAttribute(\Vendor\Package\MyClass::class, $myCustomState);
Copied!
If at all possible, it should be avoided to use a custom RenderingContext
implementation. However, currently it might still be necessary for some cases,
for example if you want to replace the default implementation of one of the other
dependencies, such as the StandardVariableProvider.
With further refactoring, we try to provide better ways for these use cases in the future.
FluidCache
The caching of Fluid templates happens by compiling the templates to PHP files
which execute much faster than a parsed template ever could. These compiled
templates can only be stored if a FluidCacheInterface-implementing object is
provided. Fluid provides one such caching implementation: the
SimpleFileCache which just stores compiled PHP code in a designated directory.
Should you need to store the compiled templates in other ways you can implement
FluidCacheInterface in your caching object.
Whether you use your own cache class or the default, the FluidCachemust be passed as third parameter for the View or it
must be assigned using :php:`$view->getRenderingContext()->setCache($cacheInstance)`
before calling :php:`$view->render()`.
ViewHelperInvoker
The ViewHelperInvoker is a class dedicated to validating current arguments of
and if valid, calling the ViewHelper's render method. It is the primary API to
execute a ViewHelper from within PHP code. The default object
supports the arguments added via initializeArguments() and
registerArgument() on the ViewHelper and provides all additional arguments
via handleAdditionalArguments() to the ViewHelper class. By default, the
ViewHelper implementations throw an exception, but this handling can be overwritten,
as demonstrated by AbstractTagBasedViewHelper.
You should replace the ViewHelperInvoker if:
You must support different ways of calling ViewHelpers such as alternative
setArguments names.
You wish to change the way the invoker uses and stores ViewHelper instances,
for example to use an internal cache.
You wish to change the way ViewHelper arguments are validated, for example
changing the Exceptions that are thrown.
You wish to perform processing on the output of ViewHelpers, for example to
remove XSS attempts according to your own rules.
Note
ViewHelper instance creation and argument retrieval is handled by the
ViewHelperResolver.
ViewHelperResolver
Most of your options for extending the Fluid language - like adding new ways
to format strings, to make special condition types or to render custom links -
are implemented as ViewHelpers. ViewHelpers are the special PHP classes that can
be called directly from a Fluid template:
<f:format.trim>{somestring}</f:format.trim>
Copied!
A ViewHelper is essentially referenced by the namespace alias and the name of the
ViewHelper, in this case f being the namespace alias and format.trim being
the name. The alias refers to a namespace definition, which is provided either directly
in the template file or via the PHP API of the ViewHelperResolver, see
Registering/importing ViewHelpers.
The ViewHelperResolver is the class responsible for turning those pieces
of information into an expected class name. By default, ViewHelpers are resolved
by combining a defined ViewHelper namespace with the ViewHelper name to a fully
qualified PHP class name: The ViewHelper class.
The <my:foo.bar /> ViewHelper would be resolved to the ViewHelper class
Vendor\MyPackage\ViewHelpers\Foo\BarViewHelper.
ViewHelperResolver delegates
New in version Fluid 4.3
In most cases, it shouldn't be necessary to replace the default
ViewHelperResolver with a custom implementation, since the default resolving
logic can be modified per ViewHelper namespace by defining a custom resolver delegate:
namespaceVendor\MyPackage;
useTYPO3Fluid\Fluid\Core\ViewHelper\UnresolvableViewHelperException;
useTYPO3Fluid\Fluid\Core\ViewHelper\ViewHelperResolverDelegateInterface;
finalclassCustomViewHelperResolverDelegateimplementsViewHelperResolverDelegateInterface{
publicfunctionresolveViewHelperClassName(string $viewHelperName): string{
// Generate a ViewHelper class name based on the ViewHelper name
$className = $this->generateViewHelperClassName($viewHelperName);
// If the ViewHelper name is invalid, throw UnresolvableViewHelperExceptionif (!class_exists($className)) {
thrownew UnresolvableViewHelperException('Class ' . $className . ' does not exist.', 1750667093);
}
return $className;
}
publicfunctiongetNamespace(): string{
returnself::class;
}
}
Copied!
If that namespace is used in a template, the custom resolver delegate will
be used to resolve the ViewHelper tag to the appropriate ViewHelper implementation:
Note that the fully qualified class name of the delegate is used as ViewHelper
namespace in the template. Fluid first checks if the specified PHP namespace refers
to an existing PHP class. As a fallback, the default ViewHelper resolving logic is
used.
ViewHelper instantiation
The main use case for replacing the ViewHelperResolver with a custom
class is to influence the way Fluid instantiates ViewHelper classes or
ViewHelperResolver delegates. The concrete implmementation heavily depends on
your use case, but in general you would extend the built-in class and
override the methods you want to customize:
The default ViewHelperResolver can be replaced on the rendering context by calling
$renderingContext->setViewHelperResolver($resolverInstance);.
TemplateProcessor
While custom TemplatePaths also allows sources
of template files to be modified before they are given to the TemplateParser, a
custom TemplatePaths implementation is sometimes overkill - and has the drawback
of completely overruling the reading of template file sources and making it up to
the custom class how exactly this processing happens.
In order to allow a more readily accessible and flexible way of pre-processing
template sources and affect key aspects of the parsing process, a
TemplateProcessorInterface is provided. Implementing this interface and the
methods it designates allows your class to be passed to the TemplateView and
be triggered every time a template source is parsed, right before parsing
starts:
$myTemplateProcessor = new MyTemplateProcessor();
$myTemplateProcessor->setDoMyMagicThing(true);
$templateView->setTemplateProcessors([
$myTemplateProcessor
]);
Copied!
The registration method requires an array - this is to let you define multiple
processors without needing to wrap them in a single class as well as reuse
validation/manipulation across frameworks and only replace the parts that need
to be replaced.
This makes the method preProcessSource($templateSource) be called on this
class every time the TemplateParser is asked to parse a Fluid template.
Modifying the source and returning it makes that new template source be used.
Inside the TemplateProcessor method you have access to the TemplateParser and
ViewHelperResolver instances which the View uses.
The result is that TemplateProcessor instances are able to, for example:
Validate template sources and implement reporting/logging of errors in a framework.
Fix things like character encoding issues in template sources.
Process Fluid code from potentially untrusted sources, for example doing XSS
removals before parsing.
Extract legacy namespace definitions and assign those to the
ViewHelperResolver for active use.
Extract legacy escaping instruction headers and assign those to the
TemplateParser's Configuration instance.
Enable the use of custom template code in file's header, extracted and used
by a framework.
Note again: these same behaviors are possible using a custom TemplatePaths
implementation - but even with such a custom implementation this
TemplateProcessor pattern can still be used to manipulate/validate the sources
coming from TemplatePaths, providing a nice way to decouple paths resolving
from template source processing.
The library source comes with a set of example scripts to study and play around with.
They are PHP entry scripts which render templates, their partials and layouts.
These files can be a starter to get an impression of Fluid general syntax and
capabilities, they're also linked within this documentation for single examples.
They can be run right away:
$ git clone git@github.com:TYPO3/Fluid.git
$ composer update
# Run a single example file:
$ php examples/example_format.php
# Run all example files:
$ find examples/ -maxdepth 1 -name \*.php -exec php {} \;
Copied!
Changelog
The Changelog lists notable deprecation and breaking changes.
Deprecation: First parameter of method TYPO3Fluid\Fluid\View\TemplatePaths->__construct()
is deprecated. The Constructor will be removed with Fluid v5.
Deprecation: Method TYPO3Fluid\Fluid\View\TemplatePaths->fillFromConfigurationArray()
has been marked as deprecated. It will log a deprecation level error message when called in
Fluid v4.
Deprecation: Method TYPO3Fluid\Fluid\View\TemplatePaths->fillDefaultsByPackageName()
has been marked as deprecated. It will log a deprecation level error message when called in
Fluid v4.
Deprecation: Method TYPO3Fluid\Fluid\View\TemplatePaths->ensureAbsolutePaths()
has been marked as deprecated. It will log a deprecation level error message when called in
Fluid v4.
Deprecation: Method TYPO3Fluid\Fluid\View\TemplatePaths->extractPathArrays()
has been marked as deprecated. It will log a deprecation level error message when called in
Fluid v4.
Deprecation: Method TYPO3Fluid\Fluid\View\TemplatePaths->getPackagePath()
has been marked as deprecated. It will log a deprecation level error message when called in
Fluid v4.
Deprecation: Method TYPO3Fluid\Fluid\View\TemplatePaths->toArray()
has been marked as deprecated. It will log a deprecation level error message when called in
Fluid v4.
Deprecation: Constant TYPO3Fluid\Fluid\View\TemplatePaths::DEFAULT_TEMPLATES_DIRECTORY
has been marked as deprecated and will be removed in Fluid v5.
Deprecation: Constant TYPO3Fluid\Fluid\View\TemplatePaths::DEFAULT_LAYOUTS_DIRECTORY
has been marked as deprecated and will be removed in Fluid v5.
Deprecation: Constant TYPO3Fluid\Fluid\View\TemplatePaths::DEFAULT_PARTIALS_DIRECTORY
has been marked as deprecated and will be removed in Fluid v5.
Deprecation: Trait TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic
has been marked as deprecated. It will log a deprecation level error message when called in
Fluid v4. It will be removed in Fluid v5.
Deprecation: Trait TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithContentArgumentAndRenderStatic
has been marked as deprecated. It will log a deprecation level error message when called in
Fluid v4. It will be removed in Fluid v5.
Deprecation: Static method renderStatic() on ViewHelpers that don't use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic
or TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithContentArgumentAndRenderStatic
have been marked as deprecated. They will log a deprecation level error message when called in
Fluid v4. renderStatic() will no longer be called in Fluid v5.
Deprecation: Variable names true, false and null will log a deprecation level error message because these
identifiers will become a Fluid language feature with v4.
2.14
Deprecation: Method TYPO3Fluid\Fluid\View\AbstractTemplateView::initializeRenderingContext()
has been marked as deprecated. It will be removed in Fluid v4.
Migration path is to call the rendering context directly via
TYPO3Fluid\Fluid\View\AbstractTemplateView::getRenderingContext()->getViewHelperVariableContainer()->setView()
Deprecation: Method TYPO3Fluid\Fluid\View\AbstractTemplateView::setCache()
has been marked as deprecated. It will be removed in Fluid v4.
Migration path is to call the rendering context directly via
TYPO3Fluid\Fluid\View\AbstractTemplateView::getRenderingContext()->setCache()
Deprecation: Method TYPO3Fluid\Fluid\View\AbstractTemplateView::getTemplatePaths()
has been marked as deprecated. It will be removed in Fluid v4.
Migration path is to call the rendering context directly via
TYPO3Fluid\Fluid\View\AbstractTemplateView::getRenderingContext()->getTemplatePaths()
Deprecation: Method TYPO3Fluid\Fluid\View\AbstractTemplateView::getViewHelperResolver()
has been marked as deprecated. It will be removed in Fluid v4.
Migration path is to call the rendering context directly via
TYPO3Fluid\Fluid\View\AbstractTemplateView::getRenderingContext()->getViewHelperResolver()
Deprecation: Method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper->overrideArgument()
has been marked as deprecated. It will log a deprecation level error message when called in
Fluid v4. It will be removed in Fluid v5.
TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper->registerArgument() now no longer throws
an exception if an argument is already defined, so calls to
TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper->overrideArgument()
can be replaced with TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper->registerArgument().
2.12
Deprecation: Method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractTagBasedViewHelper->registerUniversalTagAttributes()
has been marked as deprecated. It will log a deprecation level error message when called in
Fluid v4. It will be removed in Fluid v5.
Arbitrary tags are automatically added by AbstractTagBasedViewHelper, single ViewHelpers
find such arguments in $this->additionalArguments when the call to registerUniversalTagAttributes()
is removed.
Deprecation: Method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractTagBasedViewHelper->registerTagAttribute()
has been marked as deprecated. It will log a deprecation level error message when called in
Fluid v4. It will be removed in Fluid v5.
Arbitrary tags are automatically added by AbstractTagBasedViewHelper, single ViewHelpers
find such arguments in $this->additionalArguments when the call to registerUniversalTagAttributes()
is removed. Alternatively, arguments registered using registerArgument() can be found in
$this->arguments.
Deprecation: Test abstracts TYPO3Fluid\Fluid\Tests\BaseTestCase and
TYPO3Fluid\Fluid\Tests\UnitTestCase have been marked as deprecated and
will be removed in Fluid v4. Extend PHPUnit\Framework\TestCase directly.
2.9
Deprecation: Class TYPO3Fluid\Fluid\Core\Compiler\ViewHelperCompiler has
been obsoleted and marked as deprecated. It will be removed in Fluid v4.
Deprecation: Exception TYPO3Fluid\Fluid\Core\Compiler\StopCompilingChildrenException
has been obsoleted and marked as deprecated. It will be removed in Fluid v4.
Deprecation: Trait TYPO3Fluid\Fluid\Core\ViewHelper\Traits\ParserRuntimeOnly
has been obsoleted by inlining the code to consumers and marked as deprecated.
It will be removed in Fluid v4.
2.8
Deprecation: Method TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\ObjectAccessorNode->getAccessors()
is unused and has been marked as deprecated. It will be removed in Fluid v4.
Deprecation: Unused public constant TYPO3Fluid\Fluid\Core\Compiler\TemplateCompiler::SHOULD_GENERATE_VIEWHELPER_INVOCATION
has been marked as deprecated and will be removed in Fluid v4.
Deprecation: Unused public constant TYPO3Fluid\Fluid\Core\Variables\StandardVariableProvider::ACCESSOR_ARRAY
has been marked as deprecated and will be removed in Fluid v4.
Deprecation: Unused public constant TYPO3Fluid\Fluid\Core\Variables\StandardVariableProvider::ACCESSOR_GETTER
has been marked as deprecated and will be removed in Fluid v4.
Deprecation: Unused public constant TYPO3Fluid\Fluid\Core\Variables\StandardVariableProvider::ACCESSOR_ASSERTER
has been marked as deprecated and will be removed in Fluid v4.
Deprecation: Unused public constant TYPO3Fluid\Fluid\Core\Variables\StandardVariableProvider::ACCESSOR_PUBLICPROPERTY
has been marked as deprecated and will be removed in Fluid v4.
Deprecation: Unused public static property TYPO3Fluid\Fluid\Core\Parser\Patterns::$SCAN_PATTERN_ESCAPINGMODIFIER
has been marked as deprecated and will be removed in Fluid v4.
2.6
Deprecation: Method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractConditionViewHelper->evaluateCondition()
has been marked as deprecated. It will be removed in Fluid v4. Use verdict() instead.
2.5
Deprecation: Interface TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\Expression\ParseTimeEvaluatedExpressionNodeInterface
is unused and has been marked as deprecated. It will be removed in Fluid v4.
2.4
Deprecation: Class TYPO3Fluid\Fluid\Core\Variables\VariableExtractor
is unused and has been marked as deprecated. It will be removed in Fluid v4.
Use StandardVariableProvider instead.
Changelog 4.x
4.5
Deprecation: Using the xmlns namespace syntax with a PHP namespace instead of an url is deprecated
and will no longer work in Fluid v5.
Deprecation: Method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper::validateArguments()
has been marked as deprecated and will be removed in Fluid v5.
Deprecation: Custom implementations of the validateArguments() methods in ViewHelpers will no longer
be called in Fluid v5. Use TYPO3Fluid\Fluid\Core\ViewHelper\ViewHelperArgumentsValidatedEventInterface
instead.
Deprecation: Classes, interfaces, methods and constants related to cache warmup are deprecated and will be removed in Fluid v5:
Deprecation: The <f:cache.warmup> ViewHelper is deprecated and will be removed in Fluid v5.
Deprecation: Fluid variable names can no longer start with an underscore character (_). Adding such a variable to a template
now emits a E_USER_DEPRECATED level error and will result in an exception in Fluid v5. Note that this doesn't affect array
keys or object property names, only the name of the variable itself.
Deprecation: Replacing <![CDATA[]]> sections by empty lines is deprecated and will be removed in Fluid v5.
Method TYPO3Fluid\Fluid\Core\Parser\TemplateProcessor\NamespaceDetectionTemplateProcessor.php::replaceCdataSectionsByEmptyLines() now emits a E_USER_DEPRECATED level error.
4.4
Deprecation: Setting a template's layout with the variable layoutName is deprecated and will no longer work in Fluid v5.
Use TYPO3Fluid\Fluid\Core\Parser\ParsingState->setLayoutName() instead.
Deprecation: Constant TYPO3Fluid\Fluid\Core\Compiler\TemplateCompiler::LAYOUT_VARIABLE
has been marked as deprecated and will be removed in Fluid v5.
4.3
Deprecation: Property TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper::$childNodes
has been marked as deprecated and will be removed in Fluid v5. Use $viewHelperNode->getChildNodes()
instead.
Deprecation: Method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper::setChildNodes()
has been marked as deprecated and will be removed in Fluid v5.
Deprecation: Method TYPO3Fluid\Fluid\Core\ViewHelper\ViewHelperInterface::setChildNodes()
has been marked as deprecated and will be removed in Fluid v5.
4.2
Deprecation: Method TYPO3Fluid\Fluid\Core\ViewHelper\ViewHelperResolver::resolvePhpNamespaceFromFluidNamespace()
now emits a E_USER_DEPRECATED level error.
Deprecation: Method TYPO3Fluid\Fluid\Core\ViewHelper\ViewHelperResolver::isNamespaceValidOrIgnored()
now emits a E_USER_DEPRECATED level error.
Deprecation: Constant TYPO3Fluid\Fluid\Core\Parser\Patterns::NAMESPACESUFFIX
has been marked as deprecated and will be removed in Fluid v5.
Deprecation: Method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper::isValidType()
now emits a E_USER_DEPRECATED level error.
Deprecation: Method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper::getFirstElementOfNonEmpty()
now emits a E_USER_DEPRECATED level error.
Deprecation: Method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper::postParseEvent()
now emits a E_USER_DEPRECATED level error. It will be removed with Fluid v5. ViewHelpers using this event
should switch to the new TYPO3Fluid\Fluid\Core\ViewHelper\ViewHelperNodeInitializedEventInterface
Deprecation: Method TYPO3Fluid\Fluid\Core\ViewHelper\ViewHelperResolver::addNamespaces()
now emits a E_USER_DEPRECATED level error.
Deprecation: Inheritance of ViewHelper namespaces is deprecated. If a ViewHelper namespace is used in a
template that is neither defined globally nor locally directly in the template, Fluid now emits a
E_USER_DEPRECATED level error.
4.0
Breaking: Method TYPO3Fluid\Fluid\View\AbstractTemplateView::initializeRenderingContext()
has been removed.
Breaking: Method TYPO3Fluid\Fluid\View\AbstractTemplateView::setCache()
has been removed.
Breaking: Method TYPO3Fluid\Fluid\View\AbstractTemplateView::getTemplatePaths()
has been removed.
Breaking: Method TYPO3Fluid\Fluid\View\AbstractTemplateView::getViewHelperResolver()
has been removed.
Breaking: Change visibility of class constants that represent internal Fluid state. The
following constants have been set to protected and can only be accessed by
AbstractTemplateView and its child implementations:
TYPO3Fluid\Fluid\View\AbstractTemplateView::RENDERING_TEMPLATE,
TYPO3Fluid\Fluid\View\AbstractTemplateView::RENDERING_PARTIAL,
TYPO3Fluid\Fluid\View\AbstractTemplateView::RENDERING_LAYOUT
Breaking: Careful addition of method and property type hints throughout the system.
This should be only mildly breaking and projects should be able to adapt easily.
Deprecation: First parameter of method TYPO3Fluid\Fluid\View\TemplatePaths->__construct()
is deprecated. The Constructor will be removed with Fluid v5.
Deprecation: Method TYPO3Fluid\Fluid\View\TemplatePaths->fillFromConfigurationArray()
now emits a E_USER_DEPRECATED level error.
Deprecation: Method TYPO3Fluid\Fluid\View\TemplatePaths->fillDefaultsByPackageName()
now emits a E_USER_DEPRECATED level error.
Deprecation: Method TYPO3Fluid\Fluid\View\TemplatePaths->ensureAbsolutePaths()
now emits a E_USER_DEPRECATED level error.
Deprecation: Method TYPO3Fluid\Fluid\View\TemplatePaths->extractPathArrays()
now emits a E_USER_DEPRECATED level error.
Deprecation: Method TYPO3Fluid\Fluid\View\TemplatePaths->getPackagePath()
now emits a E_USER_DEPRECATED level error.
Deprecation: Method TYPO3Fluid\Fluid\View\TemplatePaths->toArray()
now emits a E_USER_DEPRECATED level error.
Deprecation: Constant TYPO3Fluid\Fluid\View\TemplatePaths::DEFAULT_TEMPLATES_DIRECTORY
has been marked as deprecated and will be removed in Fluid v5.
Deprecation: Constant TYPO3Fluid\Fluid\View\TemplatePaths::DEFAULT_LAYOUTS_DIRECTORY
has been marked as deprecated and will be removed in Fluid v5.
Deprecation: Constant TYPO3Fluid\Fluid\View\TemplatePaths::DEFAULT_PARTIALS_DIRECTORY
has been marked as deprecated and will be removed in Fluid v5.
Deprecation: Trait TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic
now emits a E_USER_DEPRECATED level error.
Deprecation: Trait TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithContentArgumentAndRenderStatic
now emits a E_USER_DEPRECATED level error.
Deprecation: Static method renderStatic() on ViewHelpers that don't use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic
or TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithContentArgumentAndRenderStatic now emits a
E_USER_DEPRECATED level error.
Deprecation: Method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper->overrideArgument()
now emits a E_USER_DEPRECATED level error.
Deprecation: Calling method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractTagBasedViewHelper->registerUniversalTagAttributes()
now emits a E_USER_DEPRECATED level error.
Deprecation: Calling method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractTagBasedViewHelper->registerTagAttribute()
now emits a E_USER_DEPRECATED level error.
Breaking: Method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractConditionViewHelper->evaluateCondition()
and handling has been removed.
Breaking: Method TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\ObjectAccessorNode->getAccessors()
has been removed.
Breaking: Constant TYPO3Fluid\Fluid\Core\Compiler\TemplateCompiler::SHOULD_GENERATE_VIEWHELPER_INVOCATION
has been removed.
Breaking: Constant TYPO3Fluid\Fluid\Core\Variables\StandardVariableProvider::ACCESSOR_ARRAY
has been removed.
Breaking: Constant TYPO3Fluid\Fluid\Core\Variables\StandardVariableProvider::ACCESSOR_GETTER
has been removed.
Breaking: Constant TYPO3Fluid\Fluid\Core\Variables\StandardVariableProvider::ACCESSOR_ASSERTER
has been removed.
Breaking: Constant TYPO3Fluid\Fluid\Core\Variables\StandardVariableProvider::ACCESSOR_PUBLICPROPERTY
has been removed.
Breaking: Static property TYPO3Fluid\Fluid\Core\Parser\Patterns::$SCAN_PATTERN_ESCAPINGMODIFIER
has been removed.
Breaking: Trait TYPO3Fluid\Fluid\Core\ViewHelper\Traits\ParserRuntimeOnly
has been removed.
Breaking: Interface TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\Expression\ParseTimeEvaluatedExpressionNodeInterface
and its handling has been removed.
Breaking: Class TYPO3Fluid\Fluid\Core\Variables\VariableExtractor
has been removed.
Breaking: Class TYPO3Fluid\Fluid\Core\Compiler\ViewHelperCompiler
has been removed.
Breaking: Exception TYPO3Fluid\Fluid\Core\Compiler\StopCompilingChildrenException
and its handling has been removed.
Breaking: Test abstracts TYPO3Fluid\Fluid\Tests\BaseTestCase and
TYPO3Fluid\Fluid\Tests\UnitTestCase have been removed.
Breaking: Using invalid namespace https://typo3.org instead of
http://typo3.org (https vs. http) throws an exception
Important: Minimum PHP version has been raised to ^8.2
Changelog 5.x
5.0
Breaking: Property TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper::$childNodes
has been removed.
Breaking: Method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper::setChildNodes()
has been removed.
Breaking: Method TYPO3Fluid\Fluid\Core\ViewHelper\ViewHelperInterface::setChildNodes()
has been removed.
Breaking: ViewHelper namespaces are no longer inherited from templates to layouts and partials.
Breaking: Trait TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic
has been removed.
Breaking: Trait TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithContentArgumentAndRenderStatic
has been removed.
Breaking: Static method renderStatic() on ViewHelpers that don't use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic
or TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithContentArgumentAndRenderStatic
is no longer called.
Breaking: Method TYPO3Fluid\Fluid\View\TemplatePaths->__construct()
has been removed.
Breaking: Method TYPO3Fluid\Fluid\View\TemplatePaths->fillFromConfigurationArray()
has been removed.
Breaking: Method TYPO3Fluid\Fluid\View\TemplatePaths->fillDefaultsByPackageName()
has been removed.
Breaking: Method TYPO3Fluid\Fluid\View\TemplatePaths->ensureAbsolutePaths()
has been removed.
Breaking: Method TYPO3Fluid\Fluid\View\TemplatePaths->extractPathArrays()
has been removed.
Breaking: Method TYPO3Fluid\Fluid\View\TemplatePaths->getPackagePath()
has been removed.
Breaking: Method TYPO3Fluid\Fluid\View\TemplatePaths->toArray()
has been removed.
Breaking: Constant TYPO3Fluid\Fluid\View\TemplatePaths::DEFAULT_TEMPLATES_DIRECTORY
has been removed.
Breaking: Constant TYPO3Fluid\Fluid\View\TemplatePaths::DEFAULT_LAYOUTS_DIRECTORY
has been removed.
Breaking: Method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper->overrideArgument()
has been removed.
Breaking: Method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper::isValidType()
has been removed.
Breaking: Method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper::getFirstElementOfNonEmpty()
has been removed.
Breaking: Method postParseEvent() on ViewHelpers is no longer called.
Breaking: Method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractTagBasedViewHelper->registerUniversalTagAttributes()
has been removed.
Breaking: Method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractTagBasedViewHelper->registerTagAttribute()
has been removed.
Breaking: Using the xmlns namespace syntax with a PHP namespace instead of an url is no longer possible.
Breaking: ViewHelper argument validation now uses the StrictArgumentProcessor, which might lead to
slightly different behavior within ViewHelpers or exceptions if ViewHelpers didn't validate arguments properly before.
Breaking: Classes, interfaces, methods and constants related to cache warmup have been removed:
Breaking: The <f:cache.warmup> ViewHelper has been removed.
Breaking: TYPO3Fluid\Fluid\Core\Parser\TemplateParser::parse() and
TYPO3Fluid\Fluid\Core\Parser\TemplateParser::createParsingRelatedExceptionWithContext() no longer
allow null as template identifier.
Breaking: Tag attributes that are set to null are now removed from the tag instead of being
interpreted as empty string in TYPO3Fluid\Fluid\Core\ViewHelper\TagBuilder.
Breaking: Method TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper::validateArguments()
has been removed.
Breaking: Custom implementations of the validateArguments() methods in ViewHelpers are no longer called.
Breaking: Fluid variable names can no longer start with an underscore character (_). Adding such a variable to a template
results in an exception. Note that this doesn't affect array keys or object property names, only the name of the variable itself.
Deprecation: Class TYPO3Fluid\Fluid\Core\ViewHelper\LenientArgumentProcessor
is no longer being used by Fluid v5 and will be removed with Fluid v6.
Breaking: CDATA sections are no longer removed from Fluid templates. Use <f:comment> instead
if you want to comment out code in Fluid templates.
Sitemap
Fluid ViewHelper Documentation
Rendered
Wed, 10 Dec 2025 11:42:52 +0000
This is a complete reference of all available ViewHelper that are part of
the standalone Fluid library.
This documentation is generated from PHP Source code of Fluid.
Note
This reference is part of the documentation of Fluid Standalone.
If you are working with Fluid in TYPO3 CMS, please refer to
TYPO3's ViewHelper reference instead.