Modern TypoScript Conditions will save you time & effort. In this article, You will find easy guidelines & examples of TypoScript conditions with modern Symfony expression language (in the form of an easy cheat sheet).
Since TYPO3 v9.4 LTS, The community introduced a new TypoScript condition from Symfony's expression language component. As an experienced developer, you understand well the importance and power of TypoScript. Let’s explore in-depth about old vs new TypoScript condition, Variables, and Functions of TypoScript, Create custom TypoScript condition, etc.
Well, You may have questions, Why is the Symfony expression language introduced in TYPO3? In my opinion, the main beauty which allows us to create custom TypoScript conditions. Keep reading, you will learn how ;)
If you are a beginner to TYPO3 and have a question: What's TypoScript? I recommend reading one of my famous articles, Myth: TypoScript Is a Scripting Language.
TYPO3 + Symfony collaborate together, cool, huh?
Symfony is a well-known PHP Framework - a set of reusable PHP components Explore https://symfony.com/
That’s the beauty of Open Source projects and community! TYPO3 is once again proof, It’s kind CMS which works well and can be integrated with other Open Source projects. You may be surprised, How many Symfony components are used in TYPO3 CMS? Here is the list:
- Console
- ExpressionLanguage
- Finder
- Polyfill Intl ICU
- Polyfill Intl IDN
- Polyfill Mbstring
- PropertyAccess
- PropertyInfo
- Routing
- YAML
What's Symfony Expression Language?
The ExpressionLanguage component provides an engine that can compile and evaluate expressions. An expression is a one-liner that returns a value (mostly, but not limited to, Booleans). Symfony Expression Language is used by TYPO3 in certain places. Read more
// Symfony Expressions
$expressionLanguage = new \Symfony\Component\ExpressionLanguage\ExpressionLanguage();
$expressionLanguage->evaluate('1 + 2'); // 3
$expressionLanguage->evaluate('1 + 2 === 3'); // true
$expressionLanguage->evaluate('1 + 2 < 3'); // false
Introduce TypoScript Condition with Symfony Expression
The Symfony expression language has been implemented for TypoScript conditions in both frontend and backend. The existing conditions are available as variables and/or functions.
Let’s quickly check what's the difference between old and new TypoScript conditions using the Symfony expressions language.
How to check TypoScript Conditions?
// TYPO3 <= 9.3
[Condition 1] && [Condition 2]
// TYPO3 >= 9.4
[Condition 1 && Condition 2]
Which one is the Current Language?
// TYPO3 <= 9.3
[globalVar = GP:L = 1]
// TYPO3 >= 9.4
[siteLanguage("languageId") == 1]
[siteLanguage("title") == "English"]
[siteLanguage("locale") == "en_US.UTF-8"]
Let’s Check Extension’s Parameters
// TYPO3 <= 9.3
[globalVar = GP:tx_t3terminal_blog|bla > 0]
// TYPO3 >= 9.4
[(request.getQueryParams()['tx_t3terminal_blog'])['bla'] > 0]
What's a Way to Check TypoScript Constants?
// TYPO3 <= 9.3
[globalVar = LIT:1 = {$myConstant}]
// TYPO3 >= 9.4
[{$myConstant} == 1]
How To Check The Current Page?
// TYPO3 <= 9.3 [globalVar = TSFE:id=17, TSFE:id=24] [globalVar = TSFE:page|pid=17, TSFE:page|pid=24]
// TYPO3 >= 9.4 [page["uid"] == 17] [page["uid"] in [17,24]] [getTSFE().id == 17] [getTSFE().id in [17,24]]
How To Know Current Page Properties?
// TYPO3 <= 9.3
[page|backend_layout = 1]
// TYPO3 >= 9.4
[page["backend_layout"] == 1]
What Way to Check Domain Conditions?
// TYPO3 <= 9.3
[globalString = IENV:HTTP_HOST = *.t3planet.com]
// TYPO3 >= 9.4
[like(request.getNormalizedParams().getHttpHost(), '*.t3planet.com')]
How to Check the Date Function?
// TYPO3 <= 9.3
[dayofweek = 5]
// TYPO3 >= 9.4
[date("w") == 5]
Which Are Available TypoScript Conditions Variables?
TYPO3 provides a built-in useful variable to check-in TypoScript conditions. Let’s grab one by one with examples.
1. applicationContext - To check Application Environment
Current application context as a string.
[applicationContext == "Development"]
[applicationContext matches "#^Development#"]
[applicationContext matches "#^Production/Dev#"]
[applicationContext matches "#^Production/(Dev|Staging)#"]
[applicationContext matches "#^Production/Live#"]
[applicationContext == "Production/Live/ClusterServer1"]
[applicationContext matches "#^Production/Live#" && getTSFE().isBackendUserLoggedIn()]
[not (applicationContext matches "#Production#")]
2. page - To check page properties
Current page record as an array.
[page ["pid"] == 2]
3. {$foo.bar} - To check TypoScript Constant
Any TypoScript constant is available like before. Depending on the type of the constant you have to use different conditions, see examples below.
[{$foo.bar} == 4711]
["{$foo.bar}" == "4711"]
4. tree - To check Page Tree
Object with tree information.
[tree.level == 0]
[tree.rootLine [0] ["uid"] == 1]
[2 in tree.rootLineIds]
5. backend - To check Backend User
Object with backend information (available in Backend only).
[backend.user.isAdmin]
[backend.user.isLoggedIn]
[backend.user.userId == 5]
[like ("," ~ backend.user.userGroupList ~ ",", "," *, 1, * ")]
6. frontend - To check Frontend User
Object with frontend information (available in Frontend only).
[frontend.user.isLoggedIn]
[frontend.user.userId == 5]
[like ("," ~ frontend.user.userGroupList ~ ",", "," *, 1, * ")]
7. typo3 - To check the TYPO3 environment
Object with TYPO3 related information.
[typo3.version == "10.4.2"]
[typo3.branch == "10.4"]
[typo3.devIpMask == "192.168.0.100"]
8. workspace - To check TYPO3 Workspace
Object with workspace information.
[workspace.workspaceId == 1]
[workspace.isLive]
[workspace..isOffline]
Functions for Backend and Frontend
Functions take over the logic of the old conditions which do more than a simple comparison check.
9. request - To check Request Params
To check request params with many functions.
[request.getQueryParams()['foo'] == 1]
[request.getParsedBody()['foo'] == 1]
[request.getHeaders()['Accept'] == 'json']
[request.getCookieParams()['foo'] == 1]
[request.getNormalizedParams().isHttps()]
[request.getPageArguments().get('foo_id') > 0]
[request.getNormalizedParams().getHttpHost() == "t3planet.com"]
10. date - To check Date Condition
Get the current date in the given format.
[date("d.m.Y") == "05.04.2019"]
[date("j") == 7]
11. like - To Like Search in String
This function has two parameters: the first parameter is the string to search in the second parameter is the search string.
Syntax: <array-key>[/<array-key>]*
[like("foobarbaz", "*bar*")]
[like("fooBarBaz", "f?oBa?Baz")]
[like("fooBarBaz", "/f[o]{2,2}[aBrz]+/")]
[like("fooBarBaz", "Bar")]
12. traverse - To check Traverse in String
[traverse(request.getQueryParams(), 'tx_news_pi1/news') > 0]
13. ip - To check IP Address
Value or Constraint, Wildcard or RegExp possible special value: devIP (match the devIPMask).’
[ip("172.18.*")]
[ip("devIP")]
14. compatVersion - To check TYPO3 Compat Version
Version constraint, e.g. 10.4 or 10.4.0.
[compatVersion("10.4.0")]
15. loginUser - To check Frontend User
Value or constraint, wildcard, or RegExp.
[loginUser('*')]
[loginUser("3")]
[loginUser("3,7,9")]
[loginUser("*") == false]
16. getTSFE - To check TSFE Variable
Conditions based on getTSFE() used in a context where TSFE is not available will always evaluate to false.
[getTSFE().page["uid"] == 1]
[getTSFE().fe_user && getTSFE.fe_user.user["username"] == "t3terminal"]
[getTSFE() && getTSFE().isBackendUserLoggedIn()]
17. getenv - To check ENV PHP Function
Check PHP Environment.
[getenv("VIRTUAL_HOST") == "t3planet.com"]
18. usergroup - To check User Group
Value or constraint, wildcard or RegExp possible.
[usergroup("*")]
[usergroup("12")]
[usergroup("12,15,18")]
Functions for Frontend Only
19. session - To check TYPO3 Session
Get value from the session.
[session("session:foo|bar") == 1234567]
20. site - To check Site Configuration
Get value from site configuration, or null if no site was found or property does not exist.
[site("identifier") == "t3terminal"]
[site("base").getHost() == "t3planet.com"]
[site("base").getPath() == "/"]
[site("rootPageId") == 1]
[site("languages")[0].getDirection() == "ltr"]
[site("configuration")["base"] == "/"]
[site("configuration")["direction"] == "ltr"]
[site("configuration")["enabled"] == true]
[site("configuration")["flag"] == "flags-en-us-gb"]
[site("configuration")["hreflang"] == "en-US"]
[site("configuration")["iso-639-1"] == "en"]
[site("configuration")["languageId"] == "0"]
[site("configuration")["locale"] == "en_US.UTF-8"]
[site("configuration")["navigationTitle"] == "English"]
[site("configuration")["title"] == "English"]
[site("configuration")["typo3Language"] == "default"]
21. siteLanguage - To check Language
Get value from siteLanguage configuration, or null if no site was found or property does not exist.
[siteLanguage("locale") == "de_CH"]
[siteLanguage("title") == "German"]
How to create Custom TypoScript Conditions with Symfony Expression Language?
My favorite feature of TypoScript conditions with Symfony expression language is to “Build custom conditions with unlimited extendibility”. And, It’s very easy to create your own TypoScript condition, Let’s check now!
// TYPO3 <= 9.3
[userFunc = \Vendor\Extension\UserFunc\MyUserFunc('foo')]
// TYPO3 >= 9.4
[variableA === 'valueB']
page >
page = PAGE
page.10 = TEXT
page.10.value = Matched
[GLOBAL]
Step 1: Registering new Provider within Extension
// Configuration/ExpressionLanguage.php
<?php
return [
'typoscript' => [
\Vendor\ExtensionName\ExpressionLanguage\CustomTypoScriptConditionProvider::class,
]
];
Step 2: Implement Provider within Extension
// Classes/ExpressionLanguage/CustomTypoScriptConditionProvider.php <?php namespace Vendor\ExtensionName\ExpressionLanguage; use TYPO3\CMS\Core\ExpressionLanguage\AbstractProvider;
class CustomTypoScriptConditionProvider extends AbstractProvider { public function __construct() { $this->expressionLanguageVariables = [ 'variableA' => 'valueB', ]; } }
Step 3. Usage in TypoScript Conditions
[variableA === 'valueB']
page >
page = PAGE
page.10 = TEXT
page.10.value = Matched
[GLOBAL]
Advanced Example of TypoScript Conditions with Symfony Expression Language
<?php
namespace Vendor\ExtensionName\TypoScript;
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
class CustomConditionFunctionsProvider implements ExpressionFunctionProviderInterface
{
public function getFunctions()
{
return [
$this->getWebserviceFunction(),
];
}
protected function getWebserviceFunction(): ExpressionFunction
{
return new ExpressionFunction('webservice', function () {
// Not implemented, we only use the evaluator
}, function ($existingVariables, $endpoint, $uid) {
return GeneralUtility::getUrl(
'https://t3planet.com/endpoint/'
. $endpoint
. '/'
. $uid
);
});
}
}
TypoScript Test Case
[webservice('pages', 10)]
page.10 >
page.10 = TEXT
page.10.value = Matched
[GLOBAL]
[webservice('pages', 10) === 'Expected title']
page.10 >
page.10 = TEXT
page.10.value = Matched
[GLOBAL]
Wrap-up!
Thanks for reading the article, I hope you have enjoyed and explored well about new TypoScript conditions.
- Keep best practice by using brand new TypoScript conditions using Symfony Expression Language.
- Keep in mind to migrate old TypoScript conditions to new which upgrades your TYPO3 sites.
- Keep reading documentation to be aware of all new TypoScript conditions.
- Keep feeling the power and beauty of OpenSource projects and community = TYPO3 + Symfony <3
What’s your opinion on TypoScript conditions with Symfony expression language? Or, Are you facing any issues? I would like to receive your thoughts on the comment box.
Have a Happy TypoScript!
Post a Comment
- Wow, the 21 TypoScript Conditions Cheatsheet is incredibly comprehensive!
- Wow, the 21 TypoScript Conditions Cheatsheet is incredibly comprehensive!
- Hi t3planet.com admin, You always provide useful links and resources.
- Nice Article, Very Helpful.!!
- Very helpful article.!!
Dhyana Chauhan
Tech Expert & Customer ManagerDhyana Chauhan is the customer support manager at T3Planet, having vast experience as an technology lead who loves exploring everything that’s in trend, especially TYPO3. Being a TYPO3 fanatic, in her free time, she loves…
More From Author
Dhyana Chauhan
Tech Expert & Customer ManagerDhyana Chauhan is the customer support manager at T3Planet, having vast experience as an technology lead who loves exploring everything that’s in trend, especially TYPO3. Being a TYPO3 fanatic, in her free time, she loves…
More From Author