assets.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. from webassets import Environment
  17. from webassets.ext.jinja2 import AssetsExtension
  18. def add_jinja2_ext(pelican):
  19. """Add Webassets to Jinja2 extensions in Pelican settings."""
  20. pelican.settings['JINJA_EXTENSIONS'].append(AssetsExtension)
  21. def create_assets_env(generator):
  22. """Define the assets environment and pass it to the generator."""
  23. assets_url = 'theme/'
  24. assets_src = os.path.join(generator.output_path, 'theme')
  25. generator.env.assets_environment = Environment(assets_src, assets_url)
  26. if 'ASSET_CONFIG' in generator.settings:
  27. for item in generator.settings['ASSET_CONFIG']:
  28. generator.env.assets_environment.config[item[0]] = item[1]
  29. logger = logging.getLogger(__name__)
  30. if logging.getLevelName(logger.getEffectiveLevel()) == "DEBUG":
  31. generator.env.assets_environment.debug = True
  32. def register():
  33. """Plugin registration."""
  34. signals.initialized.connect(add_jinja2_ext)
  35. signals.generator_init.connect(create_assets_env)