assets.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. assets_url = 'theme/'
  29. assets_src = os.path.join(generator.output_path, 'theme')
  30. generator.env.assets_environment = Environment(assets_src, assets_url)
  31. if 'ASSET_CONFIG' in generator.settings:
  32. for item in generator.settings['ASSET_CONFIG']:
  33. generator.env.assets_environment.config[item[0]] = item[1]
  34. if logging.getLevelName(logger.getEffectiveLevel()) == "DEBUG":
  35. generator.env.assets_environment.debug = True
  36. def register():
  37. """Plugin registration."""
  38. if webassets:
  39. signals.initialized.connect(add_jinja2_ext)
  40. signals.generator_init.connect(create_assets_env)
  41. else:
  42. logger.warning('`assets` failed to load dependency `webassets`.'
  43. '`assets` plugin not loaded.')