assets.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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_ENVIRONMENT']['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_destination = os.path.join(generator.output_path, theme_static_dir)
  30. generator.env.assets_environment = Environment(
  31. assets_destination, 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 'ASSET_DEBUG' in generator.settings:
  39. generator.env.assets_environment.debug = generator.settings['ASSET_DEBUG']
  40. elif logging.getLevelName(logger.getEffectiveLevel()) == "DEBUG":
  41. generator.env.assets_environment.debug = True
  42. for path in (generator.settings['THEME_STATIC_PATHS'] +
  43. generator.settings.get('ASSET_SOURCE_PATHS', [])):
  44. full_path = os.path.join(generator.theme, path)
  45. generator.env.assets_environment.append_path(full_path)
  46. def register():
  47. """Plugin registration."""
  48. if webassets:
  49. signals.initialized.connect(add_jinja2_ext)
  50. signals.generator_init.connect(create_assets_env)
  51. else:
  52. logger.warning('`assets` failed to load dependency `webassets`.'
  53. '`assets` plugin not loaded.')