How to attach js/css to a StreamField block when it is rendered?

Viewed 624

I know that you can include javascript in the form by using the django forms Media API and the js_initializer() method, and I've done so successfully. But I need to include a javascript and CSS file in the page when an instance of this custom block I've written gets displayed.

Is there a specific mechanism for that? Or do I just need to include the js/css files in the Page template? I'd really like to avoid including them on every single Page which has a StreamField that might have this block, since the vast majority won't, and that means a lot of wasted page load time.

1 Answers

This was previously discussed at https://github.com/wagtail/wagtail/issues/2490 - I haven't tried it, but I believe you could implement this by defining a frontend_media property on the relevant block classes that returns a django.forms.Media object, along with a function (a method on the page model is probably a good fit...) that collects those media definitions into a single object:

from django.forms import Media

class MyPage(Page):
    body = StreamField(...)

    def body_media(self):
        media = Media()
        for block_val in self.body:
            if hasattr(block_val.block, 'frontend_media'):
                media += block_val.block.frontend_media
        return media
Related