jinja2content.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. """
  2. jinja2content.py
  3. ----------------
  4. Pelican plugin that processes Markdown files as jinja templates.
  5. """
  6. from os import path
  7. from pelican import signals
  8. from pelican.readers import Markdown, MarkdownReader
  9. from pelican.utils import pelican_open
  10. from jinja2 import Environment, FileSystemLoader, ChoiceLoader
  11. class JinjaMarkdownReader(MarkdownReader):
  12. def __init__(self, *args, **kwargs):
  13. super(JinjaMarkdownReader, self).__init__(*args, **kwargs)
  14. # will look first in 'JINJA2CONTENT_TEMPLATES', by default the
  15. # content root path, then in the theme's templates
  16. # local_templates_dirs = self.settings.get('JINJA2CONTENT_TEMPLATES', ['.'])
  17. # local_templates_dirs = path.join(self.settings['PATH'], local_templates_dirs)
  18. local_dirs = self.settings.get('JINJA2CONTENT_TEMPLATES', ['.'])
  19. local_dirs = [path.join(self.settings['PATH'], folder)
  20. for folder in local_dirs]
  21. theme_dir = path.join(self.settings['THEME'], 'templates')
  22. loaders = [FileSystemLoader(_dir) for _dir
  23. in local_dirs + [theme_dir]]
  24. if 'JINJA_ENVIRONMENT' in self.settings: # pelican 3.7
  25. jinja_environment = self.settings['JINJA_ENVIRONMENT']
  26. else:
  27. jinja_environment = {
  28. 'trim_blocks': True,
  29. 'lstrip_blocks': True,
  30. 'extensions': self.settings['JINJA_EXTENSIONS']
  31. }
  32. self.env = Environment(
  33. loader=ChoiceLoader(loaders),
  34. **jinja_environment)
  35. def read(self, source_path):
  36. """Parse content and metadata of markdown files.
  37. Rendering them as jinja templates first.
  38. """
  39. self._source_path = source_path
  40. self._md = Markdown(extensions=self.settings['MARKDOWN']['extensions'])
  41. with pelican_open(source_path) as text:
  42. text = self.env.from_string(text).render()
  43. content = self._md.convert(text)
  44. metadata = self._parse_metadata(self._md.Meta)
  45. return content, metadata
  46. def add_reader(readers):
  47. for ext in MarkdownReader.file_extensions:
  48. readers.reader_classes[ext] = JinjaMarkdownReader
  49. def register():
  50. signals.readers_init.connect(add_reader)