Typo3 custom body tag with userfunc

Sometimes it’s useful to add attributes, such as css classes or id’s, to the body tag to apply custom css styling for different pages of your website. In most cases it’s enough to use the bodyTagCobject and conditional comments, but sometimes more flexibility is needed.

 The normal way of customizing the body tag in your typoscript is the following:

bodyTag >
bodyTagCObject = TEXT
bodyTagCObject.field = uid
bodyTagCObject.wrap = <body id="body-id-|" class="standard">

This code adds the page uid of each page to the id-attribute and a “standard” class. To add a different class to all subpages of page with the uid 8 for example, use the following condition comment after the above code to overwrite the standard class.

[PIDinRootline = 8]
bodyTagCObject.wrap = <body id="body-id-|" class="subpages">
[end]

If more flexibility is need it is also possible to use a userfunc and generate the body tag in a utility function. The following typoscript defines the userfunc:

bodyTag >
bodyTagCObject = USER
bodyTagCObject.userFunc = Vendor\ExtensionName\Util\BodyTagHelper->buildBodyTag

The according utility function looks like this:

<?php
namespace Vendor\ExtensionName\Util;

class BodyTagHelper {
   /**
    * @var \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer
    */
   public $cObj;

   public function buildBodyTag() {

      /* @var $objectManager \TYPO3\CMS\Extbase\Object\ObjectManager */
      $objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');

      /* @var $pageProvider \FluidTYPO3\Fluidpages\Provider\PageProvider */
      $pageProvider = $objectManager->get('FluidTYPO3\\Fluidpages\\Provider\\PageProvider');

      $pageControllerActionName = $pageProvider->getControllerActionFromRecord(array('uid' => $GLOBALS['TSFE']->id));

      if($pageControllerActionName == 'twoCol') {
         $bodyClass = 'page-two-col';
      } else {
         $bodyClass = 'page-default';
      }

      return '<body class="' . $bodyClass . '">';
   }
}

I use Fluidpages as templating engine and in this case I get the pageControllerActionName and use it as the css class. Thus I get a custom class name for each of my html templates automatically.

This is a fairly simple example and could also be implemented with typoscript. But you can do a lot more in this utility function. For example find out about content elements or data records used on the page and set the css class accordingly.