Skip to content
Grav 2.0 is officially stable. Read the announcement →
Archive

Add JavaScript to the footer

Started by Muut Archive 10 years ago · 2 replies · 1790 views
10 years ago

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.

PHP
    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

PHP
$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

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

And changing this too

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

or

PHP

$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
10 years ago

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.

10 years ago

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:

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

Then I could call the JS with the following

PHP
$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

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1362 9 years ago
Archive · by Muut Archive, 9 years ago
2 939 9 years ago
Archive · by Muut Archive, 9 years ago
2 4069 9 years ago
Archive · by Muut Archive, 9 years ago
1 2959 9 years ago
Archive · by Muut Archive, 9 years ago
3 1124 9 years ago