assets.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # -*- coding: utf-8 -*-
  2. """
  3. Asset management plugin for Pelican
  4. ===================================
  5. This plugin allows you to use the `webassets`_ module to manage assets such as
  6. CSS and JS files.
  7. The ASSET_URL is set to a relative url to honor Pelican's RELATIVE_URLS
  8. setting. This requires the use of SITEURL in the templates::
  9. <link rel="stylesheet" href="{{ SITEURL }}/{{ ASSET_URL }}">
  10. .. _webassets: https://webassets.readthedocs.org/
  11. """
  12. from __future__ import unicode_literals
  13. import os
  14. import logging
  15. from pelican import signals
  16. logger = logging.getLogger(__name__)
  17. try:
  18. import webassets
  19. from webassets import Environment
  20. from webassets.ext.jinja2 import AssetsExtension
  21. except ImportError:
  22. webassets = None
  23. def add_jinja2_ext(pelican):
  24. """Add Webassets to Jinja2 extensions in Pelican settings."""
  25. pelican.settings['JINJA_EXTENSIONS'].append(AssetsExtension)
  26. def create_assets_env(generator):
  27. """Define the assets environment and pass it to the generator."""
  28. theme_static_dir = generator.settings['THEME_STATIC_DIR']
  29. assets_src = os.path.join(generator.output_path, theme_static_dir)
  30. generator.env.assets_environment = Environment(
  31. assets_src, theme_static_dir)
  32. if 'ASSET_CONFIG' in generator.settings:
  33. for item in generator.settings['ASSET_CONFIG']:
  34. generator.env.assets_environment.config[item[0]] = item[1]
  35. if 'ASSET_BUNDLES' in generator.settings:
  36. for name, args, kwargs in generator.settings['ASSET_BUNDLES']:
  37. generator.env.assets_environment.register(name, *args, **kwargs)
  38. if logging.getLevelName(logger.getEffectiveLevel()) == "DEBUG":
  39. generator.env.assets_environment.debug = True
  40. if 'ASSET_SOURCE_PATHS' in generator.settings:
  41. # the default load path gets overridden if additional paths are
  42. # specified, add it back
  43. generator.env.assets_environment.append_path(assets_src)
  44. for path in generator.settings['ASSET_SOURCE_PATHS']:
  45. full_path = os.path.join(generator.theme, path)
  46. generator.env.assets_environment.append_path(full_path)
  47. def register():
  48. """Plugin registration."""
  49. if webassets:
  50. signals.initialized.connect(add_jinja2_ext)
  51. signals.generator_init.connect(create_assets_env)
  52. else:
  53. logger.warning('`assets` failed to load dependency `webassets`.'
  54. '`assets` plugin not loaded.')