渲染时如何将 js/css 附加到 StreamField 块? [英] How to attach js/css to a StreamField block when it is rendered?
问题描述
我知道您可以通过使用 django 表单媒体 API 和 js_initializer()
方法在 表单 中包含 javascript,我已经成功地做到了.但是当我编写的这个自定义块的一个实例被显示时,我需要在页面中包含一个 javascript 和 CSS 文件.
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.
有具体的机制吗?或者我只需要在页面模板中包含 js/css 文件?我真的很想避免将它们包含在每个具有 可能 具有此块的 StreamField 的页面上,因为绝大多数不会,这意味着浪费了很多页面加载时间.
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.
推荐答案
这之前在 讨论过https://github.com/wagtail/wagtail/issues/2490 - 我还没有尝试过,但我相信您可以通过在相关块上定义 frontend_media
属性来实现这一点返回 django.forms.Media 的类对象,以及将这些媒体定义收集到单个对象中的函数(页面模型上的方法可能很适合...):
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
这篇关于渲染时如何将 js/css 附加到 StreamField 块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!