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

时光毁灭记忆、已成空白 提交于 2019-12-01 09:24:43

问题


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:


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


来源:https://stackoverflow.com/questions/46571627/how-to-attach-js-css-to-a-streamfield-block-when-it-is-rendered

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!