Study guide · Fluid, Frontend Output and Localization
From the controller to the browser: Fluid, output and translation
The controller has loaded its conferences. Now they need to become a safe page in several languages. On this page you follow the data from the controller to the browser. Along the way you meet Fluid, custom ViewHelpers and data processors, then CSS, page titles and meta tags, and finally the language files.
The view and its view model
In the Model-View-Controller pattern, the controller fetches the data and hands it to the view. The view only presents what it receives. It does not query the database and contains no business rules. That is why the same data can have several views, for example HTML and JSON.
In TYPO3, Fluid plays the role of the view. In Extbase the controller passes data with assign(). Outside Extbase you create a view through the ViewFactoryInterface.
Our example is the extension my_extension with the model Conference. It shows a paginated list and a detail page, in German and in English. For each conference the list needs a date range, the number of talks and whether it is sold out.
A view model bundles exactly this data and its preparation in an object of its own, such as ConferenceTeaser. The controller creates it and passes it to the view. The template stays simple, because the values arrive already formatted. The domain model gets no presentation methods. And the preparation can be checked with unit tests.
Reading and writing Fluid
Fluid is the template engine of TYPO3 and a package of its own. TYPO3 14 uses Fluid 5. Since TYPO3 14, templates usually end in .fluid.html. Old files ending in .html keep working.
Variables go in single curly braces. You reach properties and array keys with a dot. Double braces as in Twig and PHP syntax do not exist in Fluid.
<h2>{conference.title}</h2>For an object, Fluid tries getTitle(), isTitle() and hasTitle() in this order, and only then a public property. So if the model only has isOnline(), the variable conference dot online returns its result. Fluid never reads protected properties directly.
ViewHelpers are PHP classes that you call as a tag or inline. The namespace f is predefined everywhere. That is why the ViewHelper f:link.page works without an import.
- The ViewHelper
f:ifoutputs a section only if the condition is met. The two branches go inf:thenandf:else. - Inline, for example inside an attribute, you use the arguments then and else. Inline calls need named arguments.
- The ViewHelper
f:switchcompares the value from expression with severalf:caseelements. If none matches,f:defaultCaseapplies. - The ViewHelper
f:forloops over a list. The argument as names the variable for the current element. - Fluid does not output anything inside
f:comment, not even as an HTML comment.
<f:if condition="{conferences}">
<f:then>
<f:for each="{conferences}" as="conference" iteration="i">
<li class="{f:if(condition: i.isFirst, then: 'first')}">{i.cycle}. {conference.title}</li>
</f:for>
</f:then>
<f:else>No conferences found</f:else>
</f:if>
<button class="{f:if(condition: conference.online, then: 'active', else: 'inactive')}">Live</button>An empty list or an empty query result counts as false in a condition, because Fluid evaluates it by its count. Alternatively you count with f:count. The iteration variable offers index starting at zero, cycle starting at one, total, isFirst, isLast, isEven and isOdd.
New in Fluid 5:
- Variable names starting with an underscore are reserved. If you create such a variable, Fluid throws an exception.
- Every template, layout and partial imports its namespaces itself. They are no longer inherited.
- Fluid outputs a CDATA section, but ignores ViewHelper tags in it and evaluates variables only in triple curly braces. This is how you embed CSS or JavaScript.
You import your own namespaces in the template with an xmlns attribute. Since TYPO3 14.1 you register them globally in the file Namespaces.php in the folder Configuration/Fluid of the extension. The older way through SYS.fluid.namespaces in TYPO3_CONF_VARS still works, but is deprecated.
Layouts, partials and components
A layout is the shared frame. The template names its layout with f:layout and provides its content in sections. The layout fetches them with the ViewHelper f:render and the argument section.
<!-- Templates/Conference/List.fluid.html -->
<f:layout name="Default" />
<f:section name="Main">…list…</f:section>
<!-- Layouts/Default.fluid.html -->
<main><f:render section="Main" /></main>
<aside><f:render section="Sidebar" optional="true" /></aside>If a section is missing, f:render throws an exception. With optional set to true it simply renders nothing. The argument default, on the other hand, sets a fallback text for a missing section or partial.
A partial is a reusable piece, such as the card of a conference. It only sees the variables you pass to it in arguments. Fluid finds it through the partialRootPaths.
A component is a pure Fluid template with typed arguments. It belongs to a component collection that you register in the file ComponentCollections.php in the folder Configuration/Fluid. After that you use it like a tag of your own, in any template and without partialRootPaths. With f:argument it defines the name and type of its arguments. With f:slot it outputs the content between its tags. ViewHelpers that look for a parent ViewHelper do not work inside components.
<f:argument name="title" type="string" />
<div class="card"><h3>{title}</h3><f:slot /></div>
<my:card title="{conference.title}"><p>Sold out</p></my:card>Safe output: XSS and escaping
With cross-site scripting, XSS for short, foreign JavaScript runs in a victim's browser, for example to take over their session. There are three kinds:
- Stored XSS: The malicious code is stored and delivered to other users.
- Reflected XSS: Malicious code from the request ends up directly in the response.
- DOM-based XSS: JavaScript in the browser inserts the malicious code into the page.
Fluid escapes every variable output with the PHP function htmlspecialchars, whatever the file extension of the template.
Three places you need to know:
- The ViewHelper
f:format.rawoutputs a value without escaping. Use it only for trusted content, never for user input. - For HTML from the rich text editor there is
f:format.html. It sends the text throughlib.parseFunc_RTE. That turns internal links into URLs and then calls the HTML sanitizer. The sanitizer only lets allowed tags and attributes through and removes script tags and event handlers, for example. - Fluid does not escape values in ViewHelper arguments. The ViewHelper has to do that itself.
Escaping also has to match the context. In JavaScript, or in a link that starts with javascript, HTML escaping is not enough. It is better to pass values for scripts as a data attribute or as JSON.
Two more things help. A Content Security Policy is an HTTP header. It defines from which sources the browser may load scripts, styles, images and other resources, and blocks injected inline scripts, for example. TYPO3 has its own API for it, in the frontend for example through a file csp.yaml in the site configuration. The browser console shows violations. The cookie attribute HttpOnly prevents JavaScript from reading session cookies. Neither replaces escaping, though.
Custom ViewHelpers
For the list we write a ViewHelper that formats the date range. Fluid 5 offers three base classes: AbstractViewHelper as the general base, AbstractTagBasedViewHelper with a TagBuilder for HTML tags, and AbstractConditionViewHelper for conditions.
You register arguments in initializeArguments() with registerArgument(). While rendering, the values are in the property arguments. Fluid 5 checks types more strictly, but converts simple types such as int to string automatically. Union types such as array or string are allowed. The method validateArguments() no longer exists.
namespace MyVendor\MyExtension\ViewHelpers;
final class DateRangeViewHelper extends AbstractViewHelper
{
public function initializeArguments(): void
{
$this->registerArgument('start', \DateTimeInterface::class, 'Start', true);
$this->registerArgument('end', \DateTimeInterface::class, 'End', true);
}
public function render(): string
{
return $this->arguments['start']->format('j') . ' to ' . $this->arguments['end']->format('j M Y');
}
}If a ViewHelper should also get its value without an argument, it calls renderChildren(). This returns the content between its tags, or the value passed inline with the arrow.
<m:format>{value}</m:format>
{value -> m:format()}By default, Fluid escapes the output of a ViewHelper. If you set the property escapeOutput to false, render() has to escape user input against XSS itself. Fluid still escapes the content between the tags, because without an explicit setting it then turns escapeChildren on.
A custom condition ViewHelper, for example for “sold out”, extends AbstractConditionViewHelper and only implements the static method verdict(). It receives the arguments and the rendering context and returns true or false. The base class takes care of then and else.
Page templates, data processors and USER
Not every output has a controller. The TypoScript object PAGEVIEW renders a whole page with Fluid. You only provide base paths. The template sits in the subfolder Pages and is named after the page layout, for example Default.fluid.html. Layouts and partials go in Layouts and Partials. Without further configuration, page, site, language and settings are available, with settings coming from site sets and constants. The variable data, on the other hand, belongs to content elements, for example with FLUIDTEMPLATE.
More data comes from data processors under dataProcessing. The template then does not have to fetch it itself.
- The processor menu builds a menu like HMENU, by default in the variable menu. Each entry offers title, link, active for the path to the current page, current for the page itself, and children for the next level.
- The processor files loads files, for example through references.fieldName from the field image, as file references into the variable files.
- The processor database-query loads records like CONTENT, so it respects hidden, deleted and translated records. Each row sits in the key data. Without as, the variable is called records.
- The processor language-menu returns, among other things, title, link, active and available for each language. If the page is not translated into a language, available is zero.
page.10 = PAGEVIEW
page.10.paths.10 = EXT:site_package/Resources/Private/Templates/
page.10.dataProcessing {
10 = menu
10.levels = 2
20 = database-query
20.table = tx_myext_partner
20.pidInList = 30
20.as = partners
30 = upcoming-conferences
30.limit = 3
}You write a custom data processor with the DataProcessorInterface. Its method process() receives the ContentObjectRenderer, the content object configuration, the processor configuration and the data processed so far. That data contains the results of earlier processors. You add to it and return it.
$limit = (int)$cObj->stdWrapValue('limit', $processorConfiguration, 3);
$as = $cObj->stdWrapValue('as', $processorConfiguration, 'upcomingConferences');
$processedData[$as] = $this->conferenceService->findUpcoming($limit);
return $processedData;If you read options with stdWrapValue(), all stdWrap properties work. You assign the short alias in Services.yaml with the tag data.processor and the key identifier. The tag also enables dependency injection without making the class public. For nested dataProcessing steps per result, you call the ContentDataProcessor and its method process().
USER and USER_INT call a PHP method through userFunc. Since TYPO3 14 this method needs the attribute AsAllowedCallable, otherwise TYPO3 throws an AllowedCallableException. The same applies to preUserFuncInt, postUserFunc and postUserFuncInt in stdWrap. The method receives the content, its configuration and the request with the attribute currentContentObject. If the class has setContentObjectRenderer(), TYPO3 calls that method too.
The output of USER is cached together with the page. For USER_INT, the page cache only holds a placeholder INT_SCRIPT. On every request only this part is rendered again, at a cost on every request. The same goes for COA and COA_INT. An Extbase plugin runs as USER. If the called action is listed in the fourth argument of configurePlugin(), it becomes USER_INT.
CSS, JavaScript and header data
The detail page needs a stylesheet and a script for a map. The AssetCollector collects CSS and JavaScript during rendering. Every asset has an identifier and appears only once. If our plugin sits on the page five times, the stylesheet is still included only once. With the same identifier, later attributes override earlier ones. You can check beforehand with hasStyleSheet().
<f:asset.css identifier="conference" href="EXT:my_extension/Resources/Public/Css/conference.css" />
<f:asset.script identifier="conference-map" src="EXT:my_extension/Resources/Public/JavaScript/map.js" />In the template you use f:asset.css and f:asset.script, in PHP addStyleSheet() and addJavaScript(). Both include the file only when the plugin is rendered. The TypoScript setting page.includeCSS, in contrast, includes it on every page.
The option priority decides the position. JavaScript with priority goes in the head, without it at the end of the body. CSS always goes in the head and is only grouped by priority. Assets from the AssetCollector come after the files from TypoScript.
New in TYPO3 14: The option useNonce is now called csp, and the old argument is deprecated. The option external is gone. Instead, you write relative URLs with the prefix URI and a colon. Concatenation and compression no longer exist in the Core. The options concatenateJs, concatenateCss, compressJs and compressCss under config have no effect. includeCSS and includeJS stay.
The PageRenderer builds the HTML frame in the frontend and the backend and renders all assets and header data. You get it through dependency injection. It offers methods such as addCssFile(), addJsFooterFile(), addJsInlineCode() and addHeaderData().
For any markup in the head, such as a preconnect link, TYPO3 14 adds the ViewHelper f:page.headerData, and f:page.footerData for the end of the page. They replace the deprecated sections HeaderAssets and FooterAssets. The ViewHelper f:asset.css is meant for stylesheets only.
Page title, meta tags and pagination
The PageTitle API decides the title in the browser tab. Several page title providers make suggestions. TYPO3 asks them in the order that config.pageTitleProviders defines with before and after. The first title that is not empty wins. The default provider record always returns a value, so your own providers must come before it.
EXT:seo adds the field seo_title to the page properties. If it is filled, this text goes into the title tag instead of the page title. The navigation title only affects menus. The websiteTitle is the name of the whole website.
For the detail page, TYPO3 14 offers three ways to show the conference title:
- In the template with the new ViewHelper
f:page.title. - In PHP with the new
RecordTitleProviderand its methodsetTitle(). - With a custom provider based on
AbstractPageTitleProvider, registered inconfig.pageTitleProviders.
Meta tags: The meta tag description gives search engines the short description for the result list. Editors maintain it in the page properties. The meta tag robots, in contrast, controls indexing.
In PHP you use the MetaTag API. The injected MetaTagManagerRegistry returns the responsible manager with getManagerForProperty(), for og:title the one for OpenGraph. With addProperty() you set the value, also with sub-properties such as og:image:width. There are also removeProperty() and removeAllProperties().
$this->metaTagManagerRegistry->getManagerForProperty('og:title')
->addProperty('og:title', $conference->getTitle());<f:page.meta property="og:title">{conference.title}</f:page.meta>If you need the same meta tag several times, you write a custom manager with the MetaTagManagerInterface. You register it with the registry in ext_localconf.php, with before and after for the order.
Pagination: The Pagination API splits long lists into pages with a fixed number of entries. A paginator loads the entries of the current page: ArrayPaginator for arrays, QueryResultPaginator for Extbase query results and, new in TYPO3 14, QueryBuilderPaginator for the QueryBuilder. A pagination only calculates the navigation. SimplePagination shows all page numbers, SlidingWindowPagination only a window around the current page.
$paginator = new QueryResultPaginator($conferences, $currentPage, 10);
$pagination = new SlidingWindowPagination($paginator, 5);
$this->view->assignMultiple(['paginator' => $paginator, 'pagination' => $pagination]);Internationalization and localization
i18n stands for internationalization, and the 18 counts the letters between i and n. It means preparing the software technically for several languages and regions:
- Texts live in language files such as XLIFF instead of in the code.
- The software uses Unicode throughout, that is UTF-8.
- Dates, numbers and currencies appear in the format of the locale.
- Layouts leave room for longer texts and for writing directions such as Arabic.
Localization, l10n for short, adapts the software to a specific region. That is more than translating. 1.234,56 in Germany becomes 1,234.56 in the USA. Plural rules differ. Images, examples and legal information must suit the region. A glossary keeps translations consistent. Give translators context, for example descriptions for the keys. Use placeholders instead of sentence fragments, because word order differs between languages.
In the site configuration you set several values for each language. These include the locale, such as de_DE.UTF-8, and the base, such as /en/. Further values are hreflang, navigationTitle and the fallbackType, such as strict or fallback. All languages share one database. Translated records point to their original through l10n_parent.
Formats: With the argument pattern, the ViewHelper f:format.date uses ICU patterns and the locale of the request, or a fixed locale if needed. So the German page shows “Oktober” and the English page “October”. The argument format, in contrast, uses the PHP function date and always returns English month names.
<f:format.date pattern="d. MMMM y">{conference.startDate}</f:format.date>
<f:format.currency currencySign="€" decimalSeparator="," thousandsSeparator=".">{price}</f:format.currency>The ViewHelper f:format.currency outputs two decimal places, and its default separators already are a comma and a dot. The currency sign follows the number after a space. So 1234.5 becomes “1.234,50 €”. The ViewHelper f:format.number separates the other way round by default, with a dot for decimals and a comma for thousands.
Translating labels with XLIFF
Fixed texts such as “Sold out” are called labels. TYPO3 stores them in XLIFF files with the extension .xlf, not in gettext files. They live in Resources/Private/Language: locallang.xlf for general labels, locallang_db.xlf for the TCA. The source file is in English and has neither target-language nor target elements. The German translation sits next to it with a language prefix, that is de.locallang.xlf.
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" target-language="de" datatype="plaintext" original="messages">
<body>
<trans-unit id="conference.soldOut">
<source>Sold out</source>
<target>Ausgebucht</target>
</trans-unit>
</body>
</file>
</xliff>Since TYPO3 14, TYPO3 also reads XLIFF 2.0, which uses unit and segment instead of trans-unit. Internally it uses the Symfony Translation component. Custom parsers are no longer supported.
So if a key is missing in de.locallang.xlf, the German page shows the English text. TYPO3 also ignores translations with approved set to no, because the setting LANG.requireApprovedLocalizations is on by default.
Translation domains are new in TYPO3 14. Instead of the long path you write my_extension.messages, a colon and the key. The prefix locallang with underscore is dropped: locallang.xlf becomes messages, locallang_db.xlf becomes db. The classic notation with LLL stays valid.
<f:translate key="conference.soldOut" domain="my_extension" />
<f:translate key="my_extension.messages:conference.soldOut" />
<f:translate key="LLL:EXT:my_extension/Resources/Private/Language/locallang.xlf:conference.soldOut" />
<f:translate key="list.count" arguments="{0: total}" />
<f:translate key="talks.count" arguments="{count: 3}" />If both domain and extensionName are set, domain wins. In an Extbase template the key from the extension's own locallang.xlf is enough. If you pass arguments as a list, TYPO3 replaces placeholders such as percent d and percent s with vsprintf. TYPO3 14 evaluates named arguments as an ICU message with placeholders in curly braces, including plural forms. The tag content only serves as a default text.
In PHP you translate with LocalizationUtility::translate() or the LanguageService. Labels in TCA and FlexForms are references as well, for example with the domain my_extension.db.
Language packs for the Core and TER extensions are translated by the community on Crowdin. You install them in the Maintenance module under Manage Language Packs or with the command language:update. Your own overrides go under LANG.resourceOverrides, which used to be called locallangXMLOverride.
Key points
- The view only presents. View models hand it data that is already prepared.
- Fluid tries get, is and has, then a public property.
- Fluid 5 forbids variables starting with an underscore and no longer inherits namespaces.
- Fluid escapes every variable.
f:format.rawturns that off,f:format.htmlis for rich text. - Fluid does not escape arguments. The ViewHelper has to do it.
- Condition ViewHelpers only implement
verdict(). - Data processors deliver ready-made variables. An alias comes from the tag data.processor.
- USER is cached, USER_INT sits in the cache as a placeholder. Every userFunc needs
AsAllowedCallable. - The AssetCollector includes each asset only once per identifier.
- New are
f:page.title,f:page.meta,f:page.headerDataandf:page.footerData. - If a translation is missing, the English source text appears.
Terms
- Data processor
- PHP class that prepares data for a Fluid template.
- Escaping
- Converting special characters so that they appear as text instead of code.
- i18n
- Internationalization, the technical preparation for several languages.
- l10n
- Localization, the adaptation to a specific language and region.
- Locale
- Language plus region, such as de_DE, which controls formats.
- PAGEVIEW
- TypoScript object that renders a Fluid page template.
- Translation domain
- Short name for a language file, such as my_extension.messages.
- View model
- Object with exactly the data a template needs.
- ViewHelper
- PHP class that you call in Fluid as a tag or inline.
- XLIFF
- XML format for translations.