template: boolean attribute can now be specified when importing a script, and default to "defer"

This commit is contained in:
Goffi 2018-01-03 00:23:36 +01:00
commit f2b0051004

View file

@ -155,17 +155,20 @@ class ScriptsHandler(object):
self.scripts = [] # we don't use a set because order may be important
dummy, self.theme, self.is_default_theme = renderer.getThemeData(template_path)
def include(self, library_name):
def include(self, library_name, attribute='defer'):
"""Mark that a script need to be imported.
Must be used before base.html is extended, as <script> are generated there.
If called several time with the same library, it will be imported once.
@param library_name(unicode): name of the library to import
@param loading:
"""
if attribute not in ('defer', 'async', ''):
raise exceptions.DataError(_(u'Invalid attribute, please use one of "defer", "async" or ""'))
if library_name.endswith('.js'):
library_name = library_name[:-3]
if library_name not in self.scripts:
self.scripts.append(library_name)
self.scripts.append((library_name, attribute))
return u''
def generate_scripts(self):
@ -174,14 +177,17 @@ class ScriptsHandler(object):
@return (unicode): <scripts> HTML tags
"""
scripts = []
tpl = u'<script src={src}></script>'
for library in self.scripts:
tpl = u'<script src={src} {attribute}></script>'
for library, attribute in self.scripts:
path = self.renderer.getStaticPath(library, self.template_root_dir, self.theme, self.is_default_theme, '.js')
if path is None:
log.warning(_(u"Can't find {}.js javascript library").format(library))
continue
path = os.path.join(self.root_path, path)
scripts.append(tpl.format(src=quoteattr(path)))
scripts.append(tpl.format(
src = quoteattr(path),
attribute = attribute,
))
return safe(u'\n'.join(scripts))