Search code examples
apipluginsassetsmoodle

How to work with css and js files in moodle plugin


I need to develop a plugin for Moodle, and i need to have some js and css files in plugin. But i have the next problem - how to work with them from installed plugin? Of course, i can hardcode their path via to moodle structure, but it's a very dirty and bad way. Also, i know that i can place all js and css code inline, but i think that it's a bad decision too. Is there a built-in way to serve assets from plugin? I tried to find it in documentations, but found nothing.

Thanks


Solution

  • I assume you want to know how to include CSS and JS files into your plugin. You can include a JS file via the command:

    $PAGE->requires->js( /relative/path/your_script.js');
    

    You can then call a JS function once the page has been downloaded with the command:

    $PAGE->requires->js_init_call ( your_JS_function_name, array_of_parameters_here, bool: on DOM ready);
    

    For example:

    $PAGE->requires->js_init_call('init', array($USER->lang), true);
    

    Be sure to make the $PAGE available with global $PAGE;, first.

    Your CSS file can be named styles.css and put into the root folder of your plugin. The file will be automatically read by the system and included. It will take precedence over (will overwrite the settings of) the system CSS files. After that you will have to reload the theme caches.