TYPO3:如何通过控制器初始化动作和页面渲染器添加CSS和JS文件? [英] TYPO3: How could I add css and js files via controller initialize action and page renderer?
问题描述
我正在使用TYPO3 8在控制器级别上的新页面渲染器,通过initializeAction添加特定于扩展名的css和js文件:
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
);
}
这有时可以正常工作,但仅在某些情况下可以.这意味着有时会正确添加css文件和js文件,有时如果我重新加载页面,则将不会正确添加文件.有什么问题吗?
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?
对于像TYPO3 7这样的旧版本,我使用了类似的东西:
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();
}
但是,这将不再适用于TYPO3 8.有什么建议吗?
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>
这样,您的控制器不需要任何资源逻辑,因此可以删除initializeAction()
方法.
This way you don't need any resource logic in your controller, thus your initializeAction()
method can be dropped.
顺便说一句:我建议使用JavaScript
作为JavaScript资源的目录名称,以与TYPO3约定保持一致.
BTW: I'd recommend using JavaScript
as directory name for JavaScript resources to stay in line with TYPO3 conventions.
这篇关于TYPO3:如何通过控制器初始化动作和页面渲染器添加CSS和JS文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!