Add JavaScript to the footer

I’m trying to render my JS script to the bottom of the page which is generated through my Plugin, I can register scripts/css fine within the header, by doing below.

    public function onTwigSiteVariables() {
        if($this->config->get('plugins.plugin_name.built_in_js')) {

            $this->grav['assets']->addJs('plugin://plugin/path/to/file.js');
        }
    }

The documentation tells me that I can do the following in PHP: Add javascript to footer

$this->grav['assets']->addJs($this->grav['base_url'] . '/user/plugins/yourplugin/js/somefile.js', {group: 'bottom'});

However, this doesn’t seem to work, and instead throws me a WSOD error

$this->grav['assets']->addJs('plugin://plugin/path/to/file.js', {group: 'bottom'});

And changing this too

$this->grav['assets']->addJs('plugin://plugin/path/to/file.js', array('group' => 'bottom'));

or

$this->grav['assets']->add('plugin://plugin/path/to/file.js', array('group' => 'bottom'));
--- 
Doesn't render anything in the output.

So I'm a bit lost as too how I would go about doing this.

Am I missing something here?

Any help is greatly appreciated.

Nathan

The problem is likely that the theme does not have the group bottom registered, and thus {{ assets.js('bottom') }} can not be rendered anywhere. Make sure that the template-file used as a footer includes {{ assets.js('bottom') }}.

The last two are likely ignored as the whole asset-injection silently fails if the file cannot be found. Also, be sure to turn on debug for Twig in your system.yaml so these errors are boldly proclaimed by Grav.

Thank you! I was thinking of something along these lines, but I was hoping that this wouldn’t be the case. The way I got this working was to have the following at the bottom of the template:

        {% block bottom %}
            {% include 'partials/javascripts.html.twig' %}
            {{ assets.js('bottom')|raw }}
        {% endblock %}

Then I could call the JS with the following

$this->grav['assets']->addJs('plugin://plugin/path/to/file.js', array('group' => 'bottom'));

I’ve requested an update to the documentation for this particular section.

1 Like