Search code examples
typo3typoscript

TYPO3 bring information to the JS environment


I would like to bring information like page id and root page id into the JS environment.

I thinking of manipulating or generating a JS file via TypoScript, but I have no idea how.

I know I can achieve it via controller and route enhancer. But that would be very much code.

For security reasons, I don't want inline JS.

Thank you for your time.


Solution

  • I also prefer the approach of Wolffc to add the data as data-atrributes and fetch them in the js. I would suggest to pass the data as json-string. Then you only have to fetch one data variable in your js. I think thats the easiest and fastest way to pass variables to js.

    But if you really want to go the TypoScript way. I would suggest to use a dynamic js-script.

    Here is what to do:

    First you need a USER_INT in your headerData. Add following TypoScript. Before check in your TypoScript-Object-Browser if 20 is occupied. If it is use a free number. And of course adjust the VENDOR and ExtName to your extension.

    page.headerData{
      20 = USER_INT
      20 {
        userFunc = VENDOR\ExtName\UserFunc\HeaderManipulator->addDynamicJs
      }
    }
    

    Then you will need the js template. Create a file in your extension. /Resources/Private/Templates/Js/MyDynamicJs.js

    let rootPageId = ###ROOT_PAGE_ID###;
    let pageId = ###PAGE_ID###;
    
    console.log('The Root-Page-Uid is: ' + rootPageId);
    console.log('The Page-Uid is: ' + pageId);
    

    At least you will need the User-Function to manipulate your dynamic js file. For that add following file to your extension.

    Classes/UserFunc/HeaderManipulator.php

    Adjust the VENDOR and ExtName in the namespace to fit your extension. And dont forget to adjust the extname in the file_get_contents path.

    <?php
    namespace VENDOR\ExtName\UserFunc;
    
    use TYPO3\CMS\Core\Core\Environment;
    use TYPO3\CMS\Core\Http\ServerRequest;
    
    class HeaderManipulator
    {
    
        public function addDynamicJs($content, $conf, ServerRequest $request)
        {
            $rootPageId = $request->getAttribute("site")->getRootPageId();
            $pageId = $request->getAttribute("routing")->getPageId();
    
            // Replace ext_name with your extensions name
            $js = file_get_contents(Environment::getExtensionsPath() . '/ext_name/Resources/Private/Templates/Js/MyDynamicJs.js');
            $js = str_replace('###ROOT_PAGE_ID###', $rootPageId, $js);
            $js = str_replace('###PAGE_ID###', $pageId, $js);
    
            return "<script type='text/javascript'>$js</script>";
        }
    }