Add asset (JS) to modular page?

Hi
I’ve got a modular page and one module in it needs some javascript but since its only one module I was trying to avoid adding it sitewide.

I’ve tried adding this to my modular twig file but it just gets ignored when its rendered.

    {% do assets.addJs('theme://js/icons.min.js') %}
{% endblock %}

Is your modular page implementing assets.js() or inheriting it from base.html.twig?
You need to have this somewhere in your template in order for js to be added to the page:

{{ assets.js() }}
---

My base has asset.js and my modular.twig.html file extends the base
-{% extends 'partials/base.html.twig' %} -
so I think I’ve got this covered no?

I’ve adding

 {{ parent() }} 

to modular.twig.html and that did nothing and I tried adding it to the modular page and Grav blew up

Calling parent() will not instantiate the parent, only return its object. In the context of modular-pages, their children - or modules - are not capable of adding assets upwards because they do not extend the base(.html.twig). Since your JS will be rendered page-wide for the modular, add it in modular.html.twig, as this template extends base.

ah I understand now. I was thinking it was down to the inheritance levels in twig but this makes sense. I’ve got it working now by updating the modular.twig.html with my JS. Thanks a lot

Adding JS assets to the modular template modular.html.twig is not a clean solution as other modular pages still use the modular template. There should be a standard way of injecting one-off CSS and JS assets from modules in my opinion.

3 Likes