custom_article_urls.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 Article, 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. ignore = False
  26. if ('url', 'save_as') in metadata:
  27. """ if both url and save_as are set in the metadata already
  28. then there is already a custom url set, skip this one
  29. """
  30. ignore = True
  31. elif ('status' in metadata) and (metadata['status'] == 'draft'):
  32. ignore = True
  33. if not ignore:
  34. temp_article = Article("", metadata=metadata)
  35. url_format = pattern_matched['URL']
  36. save_as_format = pattern_matched['SAVE_AS']
  37. url = url_format.format(**temp_article.url_format)
  38. save_as = save_as_format.format(**temp_article.url_format)
  39. metadata.update({'url': url, 'save_as': save_as})
  40. def register():
  41. signals.article_generator_context.connect(custom_url)