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?
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.
In TYPO3 8 getPageRenderer()
Method is Deprecated. You can see here Deprecated Methods.
Now you can use this methods in TYPO3 8 Like this solution
来源:https://stackoverflow.com/questions/45440189/typo3-how-could-i-add-css-and-js-files-via-controller-initialize-action-and-pag