pluginscontent-management-systemassetbundle

Craft CMS plugin AssetBundle Causeing Craft.js Error in Backend


Plugin routes the following url in the admin area to a controller.

url: /admin/custom_route

The controller loads the plugin asset bundle that is CpAssets::class dependent & loads the twig template everything loads but browser console gives an error for Craft.js that Craft is not defined inside the Jquery exenteded plugin function. Where Craft.js & Craft.min.js are both being loaded when only one of them should be.

Been looking at the yii functionality but I'm at a loss.


Solution

  • Solution for anyone who else who is confused with the same problem.

    In your template.twig you need to add head tags & call the head function this eliminates the Craft.js error.

    <head>
    {{ head() }}
    </head>
    

    I found the solution by looking at src/web/assets/cp/CpAsset.php where at line 98 - 103 it defines the missing js Craft object.

    // Define the Craft object
    $craftJson = Json::encode($this->_craftData(), JSON_UNESCAPED_UNICODE);
    $js = <<<JS
    window.Craft = {$craftJson};
    JS;
    $view->registerJs($js, View::POS_HEAD);
    

    Where View::POS_HEAD defines the position in the document where the script is loaded according to the yii documentation. Just calling

    {{ head() }}
    

    Will not work it need to be within the head element tags of the document.