Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

rendering - TYPO3: How could I add css and js files via controller initialize action and page renderer?

I am using the new page renderer from TYPO3 8 on controller level to add extension specific css and js files via an initializeAction:

public function initializeAction()
{
    $extPath = ExtensionManagementUtility::siteRelPath(
        $this->request->getControllerExtensionKey()
    );

    $extJs = $extPath . 'Resources/Public/Js/ext_booking_manager.min.js';
    $extCss = $extPath . 'Resources/Public/Css/ext_booking_manager.css';

    /** @var PageRenderer $pageRenderer */
    $pageRenderer = $this->objectManager->get(PageRenderer::class);

    $pageRenderer->addCssFile($extCss);
    $pageRenderer->addJsFooterFile(
        $extJs, 'text/javascript', false
    );
}

This is working fine sometimes, but only sometimes. This means that sometimes the css file and js file will be properly added and sometimes if I reload the page then the files will not be added properly. Is there something wrong?

For older versions like TYPO3 7, I used something similar like this:

public function initializeAction()
{
    $extPath = ExtensionManagementUtility::siteRelPath(
        $this->request->getControllerExtensionKey()
    );

    $extJs = $extPath . 'Resources/Public/Js/ext_booking_manager.min.js';
    $GLOBALS['TSFE']->getPageRenderer()->addJsFooterFile(
        $extJs, 'text/javascript', false
    );

    parent::initializeAction();
}

But this will not work for TYPO3 8 anymore. Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Notice that there is a different approach available in TYPO3 v8 using the HeaderAssets and FooterAssets sections in your template. Thus your action template could look like this:

Your template code

<f:section name="FooterAssets">
  <link rel="stylesheet" href="{f:uri.resource(path: 'Css/ext_booking_manager.css')}"/>
  <script src="{f:uri.resource(path: 'Js/ext_booking_manager.min.js')}"></script>
</f:section>

This way you don't need any resource logic in your controller, thus your initializeAction() method can be dropped.

BTW: I'd recommend using JavaScript as directory name for JavaScript resources to stay in line with TYPO3 conventions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...