Reputation: 633
Sometimes I need to add some js or css or both for a specific TYPO3 plugin. So far I included this via extension specific setup.txt like the following:
page.includeJSFooter.js = {$plugin.tx_fox_p1.settings.js}
page.includeCSS.css = {$plugin.tx_fox_p1.settings.css}
But if I add this static extension typoscript to the root template it will include the js and css on every page don't care if it is needed or not. Too avoid this I could create an extension template for every page where the plugin is placed, but when the plugin representing for example a sidebar tool and the site contains a lot of pages which uses this tool then this will be not so nice, to set an extension template for all this pages.
Maybe there is a way to add a plugin to a specific page and don't care about including css and js because it will include this dynamically and only on pages where the plugin is placed?
Maybe a typoscript condition?
Upvotes: 3
Views: 2692
Reputation: 337
I use this code for dynamic JS loading in Extbase controller:
class ShopController extends \Vendor\Shop\Controller\AbstractController {
/**
* Init
*
* @return void
*/
public function initializeAction() {
$ajax = ExtensionManagementUtility::siteRelPath($this->request->getControllerExtensionKey()).'Resources/Public/JavaScripts/Ajax.js';
$GLOBALS['TSFE']->getPageRenderer()->addJsFooterFile($ajax, 'text/javascript', FALSE, FALSE, '');
parent::initializeAction();
}
}
Upvotes: 3
Reputation: 55798
In your controller's action you can include header parts with at least two ways:
public function yourAction() {
// This will append each to the header
$this->response->addAdditionalHeaderData('<script src="/foo/bar/one.js"></script>');
$this->response->addAdditionalHeaderData('<script src="/foo/bar/two.js"></script>');
// This will override headers with the same key, so make sure if it's absolutely unique
// (usualy some prefix + ext_key creates unique keys...
$GLOBALS['TSFE']->additionalHeaderData['absolutely_unique_key'] = '<script src="/foo/bar/unique.js"></script>';
$GLOBALS['TSFE']->additionalHeaderData['absolutely_unique_key'] = '<script src="/foo/bar/override.js"></script>';
// your other code...
}
Upvotes: 3
Reputation: 7036
Indeed, you could wrap your Includes in a TypoScript condition:
[globalVar = TSFE:id = 10|12|15]
page.includeJSFooter.js = {$plugin.tx_fox_p1.settings.js}
page.includeCSS.css = {$plugin.tx_fox_p1.settings.css}
[END]
With the above TS your CSS and JS will only be included on pages 10, 12 and 15. There are more possibilities with TS conditions, as documented here.
Upvotes: 1