custom_article_urls.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # -*- coding: utf-8 -*-
  2. """
  3. @Author: Alistair Magee
  4. Adds ability to specify custom urls for different categories
  5. (or subcategories if using subcategory plugin) of article
  6. using a dictionary stored in pelican settings file as
  7. {category: {article_url_structure: stirng, article_save_as: string}}
  8. """
  9. from pelican import signals
  10. from pelican.contents import Content, Category
  11. from six import text_type
  12. def custom_url(generator, metadata):
  13. if 'CUSTOM_ARTICLE_URLS' in generator.settings:
  14. custom_urls = generator.settings['CUSTOM_ARTICLE_URLS']
  15. category = text_type(metadata['category'])
  16. pattern_matched = {}
  17. if category in custom_urls:
  18. pattern_matched = custom_urls[category]
  19. if 'subcategories' in metadata: #using subcategory plugin
  20. for subcategory in metadata['subcategories']:
  21. if subcategory in custom_urls:
  22. pattern_matched = custom_urls[subcategory]
  23. if pattern_matched:
  24. #only alter url if hasn't been set in the metdata
  25. if ('url', 'save_as') in metadata:
  26. """ if both url and save_as are set in the metadata already
  27. then there is already a custom url set, skip this one
  28. """
  29. pass
  30. else:
  31. temp_article = Content(None, metadata=metadata)
  32. url_format = pattern_matched['URL']
  33. save_as_format = pattern_matched['SAVE_AS']
  34. url = url_format.format(**temp_article.url_format)
  35. save_as = save_as_format.format(**temp_article.url_format)
  36. metadata.update({'url': url, 'save_as': save_as})
  37. def register():
  38. signals.article_generator_context.connect(custom_url)