The Contao cms supports dynamic content integration through the so called "insert-tags". Contao has a lot of built in "insert-tags" but sometimes when writing custom extensions may be the need to create a custom one.
Our custom “insert tags”
For the purpose of this tutorial we will create an extension for Contao that that provides two “insert tags” in order to display:
- The ip address of the visitor when called as {{mytag::ip_address}}
- The current page title when called as {{mytag::page_title}}
please note that the above functionalities are provided by the default {{env::ip}} and {{env::page_title}} “insert tags”.
Prepare the directory structure And files
Create the following files and directory under TL_ROOT/system/modules
[D]: directory - [F]: file
----------------------------------------------
[D] my_inserttags/
[D] config/
[F] config.php
[F] MyInsertTags.php
Let’s start
Contao provides the insert-tags functionality through the replaceInsertTags hook, so the creation of a custom "insert tags" is a simple two step operation:
Step 1:
Put the following code into my_inserttags/config/config.php
<?php
$GLOBALS['TL_HOOKS']['replaceInsertTags'][] = array('MyInsertTags', 'outputTagContent');
?>
Step 2:
Put the following code into my_inserttags/MyInsertTags.php
<?php
class MyInsertTags extends Controller {
public function outputTagContent($strTag) {
/**
* we need to run our function only if the $strTag argument is one of:
* mytag::ip_address
* or
* mytag::page_title
*/
$arrParts = explode('::', $strTag);
/**
* returning false means that our function can not recognize the tag
* so Contao will try if the next hook applies
*/
if ($arrParts[0] != 'mytag') {
return false;
}
switch ($arrParts[1]) {
case 'ip_address':
/**
* here goes the code that match our mytag::ip_address tag
*/
return $this->Environment->ip;
break;
case 'page_title':
/**
* here goes the code that match our mytag::page_title tag
*/
return $GLOBALS['objPage']->pageTitle;
break;
}
/**
* mytag::something is still an unrecognized tag
*/
return false;
}
}
?>
We are done
Our estension is ready to run. We can test it by creating a content element through the Contao backend and put the following lines in it:
You ip address is: {{mytag::ip_address}}
The page title is: {{mytag::page_title}}
If you have questions or comments do not hesitate to comment below.
Thank you for this article. It helped me a lot.
ReplyDeleteIt works great!! Thank you very much!
ReplyDeleteGreat information about insert tags. Thanks for sharing.
ReplyDeleteEasy understanding
ReplyDeleteThank you.
Hi... I read your post, its very helpful for me,,, Thanks for sharing this informative post..
ReplyDelete