The replaceInsertTags
hook is triggered when an unknown insert tag is found. This allows you to implement your own
custom insert tags. The hook passes the insert tag (i.e. everything between {{
and }}
, but without the flags) as an
argument and expects the replacement value or false as return value.
See also the dedicated framework article about Insert Tags.
Using the replaceInsertTags
hook has been deprecated and will no longer work in Contao 6. See
here on how to register custom insert tags.
string $insertTag
The unknown insert tag.
bool $useCache
Indicates if we are supposed to cache.
string $cachedValue
The cached replacement for this insert tag (if there is any).
array $flags
An array of flags used with this insert tag.
array $tags
Contains the result of spliting the page’s content in order to replace the insert tags.
array $cache
The cached replacements of insert tags found on the page so far.
int $_rit
Counter used while iterating over the parts in $tags
.
int $_cnt
Number of elements in $tags
.
Return a string if your function is taking care of this insert tag. The hook loop will be stopped and your output is used as a replacement value.
If your function is not responsible for this insert tag, you must return
false
to continue to the next hook callback.
If you have a simple insert tag called {{mytag}}
then all you need is the following:
// src/EventListener/ReplaceInsertTagsListener.php
namespace App\EventListener;
use Contao\CoreBundle\DependencyInjection\Attribute\AsHook;
#[AsHook('replaceInsertTags')]
class ReplaceInsertTagsListener
{
public function __invoke(string $tag)
{
if ('mytag' !== $tag) {
return false;
}
return 'mytag replacement';
}
}
If your insert tag also supports parameters, e.g. {{mytag::foobar}}
then you need to parse these parameters yourself.
For example:
// src/EventListener/ReplaceInsertTagsListener.php
namespace App\EventListener;
use Contao\CoreBundle\DependencyInjection\Attribute\AsHook;
#[AsHook('replaceInsertTags')]
class ReplaceInsertTagsListener
{
public function __invoke(string $tag)
{
[$name, $param] = explode('::', $tag) + [null, null];
if ('mytag' !== $name) {
return false;
}
return 'mytag replacement with parameter: '.$param;
}
}
The hook also passes various additional parameters - for example all the flags that have been appended to the insert tag, or the cached values of all insert tags that occurred previously.
// src/EventListener/ReplaceInsertTagsListener.php
namespace App\EventListener;
use Contao\CoreBundle\DependencyInjection\Attribute\AsHook;
#[AsHook('replaceInsertTags')]
class ReplaceInsertTagsListener
{
public function __invoke(
string $tag,
bool $useCache,
string $cachedValue,
array $flags,
array $tags,
array $cache,
int $_rit,
int $_cnt
)
{
if ('mytag' !== $tag) {
return false;
}
// …
return 'mytag replacement';
}
}