How to load JavaScript or stylesheet conditionally depends on backend config settings?

ifconfig
configuration
css
asset
javascript
stylesheet
page-rendering
(Dmitry Fedyuk) #1

Step 1

Add a block to the layout.
If your condition is simple then you can use ifconfig.
If your condition is complex then do not worry because in the block class you can implement your condition in PHP.

Dfe/Markdown/view/adminhtml/layout/default.xml:

<?xml version='1.0'?>
<page 
	xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
	xsi:noNamespaceSchemaLocation='../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd'>
	<body>
		<referenceContainer name='root'>
			<block
				class='Dfe\Markdown\Block\Init'
				name='Dfe_Markdown_Block_Init'
				ifconfig='dfe_backend/markdown/enable'
			/>
		</referenceContainer>
	</body>
</page>

Step 2

Call the \Magento\Framework\View\Page\Config::addPageAsset() method on your block’s construction.
If you have a complex condition then here is the right place to implement it:

Dfe/Markdown/Block/Init.php:

<?php
namespace Dfe\Markdown\Block;
class Init extends \Magento\Backend\Block\AbstractBlock {
	/**
	 * @override
	 * @see \Magento\Backend\Block\AbstractBlock::_construct()
	 * @return void
	 */
	protected function _construct() {
		/** http://devdocs.magento.com/guides/v2.0/architecture/view/page-assets.html#m2devgde-page-assets-api */
		/** @var \Magento\Framework\App\ObjectManager $om */
		$om = \Magento\Framework\App\ObjectManager::getInstance();
		/** @var \Magento\Framework\View\Page\Config $page */
		$page = $om->get('Magento\Framework\View\Page\Config');
		$page->addPageAsset('Dfe_Markdown::main.js');
		$page->addPageAsset('Dfe_Markdown::main.css');
	}
}

Step 3

Dfe/Markdown/view/adminhtml/web/main.js:

require(['jquery'], function($) {$(function() {
	console.log('HELLO, WORLD!');
});});
0 Likes

How to add JavaScript / CSS / Less with a custom module
How to insert some JavaScript to a *.phtml template in the proper way (x-magento-init)
How can an extension conditionally show (or hide) a block
How to pass parameters from *.phtml to a JavaScript component using x-magento-init
How to add a stylesheet to a page after the layout has already been built?
How is Magento\Framework\View\Page\Config::addPageAsset() implemented and used?
How to add a stylesheet to a page after the layout has already been built?
(Dmitry Fedyuk) #2

See also:

0 Likes

(Gogol Sengupta) #3

Works pretty well, however now my css/js files won’t deploy when I do php bin/magento setup:static-content:deploy . Any way to do that? Many thanks for the article nevertheless. I was searching for a dynamic solution for ages lol :stuck_out_tongue:

0 Likes

(Dmitry Fedyuk) #4

What exact system behaviour / state you have denoted with the term won’t deploy?

0 Likes

(Gogol Sengupta) #5

That’s what I call quick reply! Thanks! Let me explain the problem.

Here’s my layout:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
	<body>
		<referenceContainer name='root'>
			<block
				class='Sbr\Admintheme\Block\Init'
				name='Sbr_Admintheme_Block_Init'
				
			/>
		</referenceContainer>
	</body>
</page>

Here’s the block code:

<?php

namespace Sbr\Admintheme\Block;

class Init extends \Magento\Backend\Block\AbstractBlock {

    /**
     * @override
     * @see \Magento\Backend\Block\AbstractBlock::_construct()
     * @return void
     */
    protected function _construct() {
        $om = \Magento\Framework\App\ObjectManager::getInstance();
        $helper = $om->get('Sbr\Admintheme\Helper\Data');
        if ($helper->isAdmin()) {
            $page = $om->get('Magento\Framework\View\Page\Config');
            $page->addPageAsset('Sbr_Admintheme::app.js');
            $page->addPageAsset('Sbr_Admintheme::app.css');
        }
    }

}

Please note, that I am using a custom helper method called isAdmin() to check if the user is a super admin (which might not be important here, but anyway).

Now, if I check the source code in admin, it does show the files ( script tag not allowed here i guess. Added space after starting < )

 < script type="text/javascript" src="http://mage.dev/pub/static/adminhtml/Sbr/Admintheme/en_US/Sbr_Admintheme/app.js"></ script>


 < link rel="stylesheet" type="text/css" media="all" href="http://mage.dev/pub/static/adminhtml/Sbr/Admintheme/en_US/Sbr_Admintheme/app.css"/>

but those files do not exist in the static folder. Even if I run bin/magento setup:static-content:deploy

However, if I use the following layout, my css and js files are copied without a problem:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="Sbr_Admintheme::css/app.css" order="1000"/>
        <link src="Sbr_Admintheme::js/app.js" order="1001"/>
        
    </head>
    <body>
    
    </body>
</page>

I believe some kind of reference to those files should also be added somewhere but not sure. Please feel free to ask me if you need any other detail.

Thank you so much!

0 Likes

(Dmitry Fedyuk) #6

You should not be worried about these files’ absence in the pub/static folder: Magento 2 should successfully locate them on demand.

1 Like