pelican_css_js.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. """
  2. Include JavaScript and CSS files for Pelican
  3. ============================================
  4. This plugin allows you to easily embed JS and CSS in the header of individual
  5. articles.
  6. """
  7. import os
  8. import shutil
  9. from pelican import signals
  10. def copy_resources(src, dest, file_list):
  11. """
  12. Copy files from content folder to output folder
  13. Parameters
  14. ----------
  15. src: string
  16. Content folder path
  17. dest: string,
  18. Output folder path
  19. file_list: list
  20. List of files to be transferred
  21. Output
  22. ------
  23. Copies files from content to output
  24. """
  25. if not os.path.exists(dest):
  26. os.makedirs(dest)
  27. for file_ in file_list:
  28. file_src = os.path.join(src, file_)
  29. shutil.copy2(file_src, dest)
  30. def add_files(gen, metadata):
  31. """
  32. The registered handler for the dynamic resources plugin. It will
  33. add the javascripts and/or stylesheets to the article
  34. """
  35. site_url = gen.settings['SITEURL']
  36. formatters = {
  37. 'styles': '<link rel="stylesheet" href="{0}" type="text/css" />',
  38. 'js': '<script src="{0}"></script>'
  39. }
  40. dirnames = {'styles': 'css',
  41. 'js': 'js'}
  42. for key in ['styles', 'js']:
  43. if key in metadata:
  44. files = metadata[key].replace(" ", "").split(",")
  45. htmls = []
  46. for f in files:
  47. if f.startswith('http://') or f.startswith('https://'):
  48. link = f
  49. else:
  50. if gen.settings['RELATIVE_URLS']:
  51. link = "%s/%s/%s" % ('..', dirnames[key], f)
  52. else:
  53. link = "%s/%s/%s" % (site_url, dirnames[key], f)
  54. html = formatters[key].format(link)
  55. htmls.append(html)
  56. metadata[key] = htmls
  57. def move_resources(gen):
  58. """
  59. Move files from js/css folders to output folder
  60. """
  61. js_files = gen.get_files('js', extensions='js')
  62. css_files = gen.get_files('css', extensions='css')
  63. js_dest = os.path.join(gen.output_path, 'js')
  64. copy_resources(gen.path, js_dest, js_files)
  65. css_dest = os.path.join(gen.output_path, 'css')
  66. copy_resources(gen.path, css_dest, css_files)
  67. def register():
  68. """
  69. Plugin registration
  70. """
  71. signals.article_generator_context.connect(add_files)
  72. signals.page_generator_context.connect(add_files)
  73. signals.article_generator_finalized.connect(move_resources)