Replace the MenuItem.render_js mechanism with the 'media' mechanism from django.forms, which does basically the same thing but better (e.g. handles de-duping where multiple items import the same js file)

This commit is contained in:
Matt Westcott 2014-08-14 15:46:24 +01:00
parent 07d2851e37
commit 72c3888505
3 changed files with 11 additions and 20 deletions

View file

@ -1,6 +1,6 @@
from __future__ import unicode_literals
from six import text_type
from six import text_type, with_metaclass
try:
# renamed util -> utils in Django 1.7; try the new name first
@ -9,13 +9,14 @@ except ImportError:
from django.forms.util import flatatt
from django.conf import settings
from django.forms import MediaDefiningClass
from django.utils.text import slugify
from django.utils.html import format_html, format_html_join
from wagtail.wagtailcore import hooks
class MenuItem(object):
class MenuItem(with_metaclass(MediaDefiningClass)):
def __init__(self, label, url, name=None, classnames='', attrs=None, order=1000):
self.label = label
self.url = url
@ -28,19 +29,6 @@ class MenuItem(object):
else:
self.attr_string = ""
js_files = []
def render_js(self):
"""
Return a string of any Javascript declarations required by this menu item.
These will be included on all admin pages, regardless of whether the menu item
is actually shown or not - this allows us to cache/compress the JS globally.
By default this returns a script tag for every file listed in self.js_files.
"""
if self.js_files:
return format_html_join('\n', '<script src="{0}{1}"></script>',
((settings.STATIC_URL, filename) for filename in self.js_files)
)
def is_shown(self, request):
"""
Whether this menu item should be shown for the given request; permission

View file

@ -2,6 +2,7 @@ from __future__ import unicode_literals
from django.conf import settings
from django import template
from django.forms import Media
from wagtail.wagtailcore import hooks
from wagtail.wagtailcore.models import get_navigation_menu_items, UserPagePermissionsProxy, PageViewRestriction
@ -41,8 +42,11 @@ def main_nav(context):
@register.simple_tag
def main_nav_js():
js_snippets = [item.render_js() or '' for item in get_master_menu_item_list()]
return ''.join(js_snippets)
media = Media()
for item in get_master_menu_item_list():
media += item.media
return media['js']
@register.filter("ellipsistrim")

View file

@ -6,9 +6,8 @@ from wagtail.wagtailadmin.menu import MenuItem
class ExplorerMenuItem(MenuItem):
js_files = [
'wagtailadmin/js/explorer-menu.js',
]
class Media:
js = ['wagtailadmin/js/explorer-menu.js']
@hooks.register('register_admin_menu_item')
def register_explorer_menu_item():