Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.md 1.5KB

1234567891011121314151617181920212223242526272829303132
  1. title: Markdown et Python
  2. [Suite](/david/stream/2015/01/25/) des utilitaires utilisés pour générer ce site.
  3. J’ai une arborescence de fichiers markdown que je transforme en fichiers `HTML`. Je commence donc par les récupérer :
  4. :::python
  5. def each_markdown_from(source_dir, file_name='index.md'):
  6. """Walk across the `source_dir` and return the md file path."""
  7. for root, dirnames, filenames in os.walk(source_dir):
  8. for filename in fnmatch.filter(filenames, file_name):
  9. yield os.path.join(root, filename)
  10. Ce petit utilitaire parcoure un dossier et retourne le chemin d’accès s’il contient `index.md`. J’ai une seconde fonction qui me permet de parser un fichier markdown et de compiler le contenu avec ses méta-données :
  11. :::python
  12. def parse_markdown(file_path, extensions=None):
  13. """Parse an md file and returns its converted content and metadata."""
  14. if extensions is None:
  15. extensions = ['meta', 'codehilite']
  16. parser = markdown.Markdown(extensions=extensions)
  17. with codecs.open(file_path, 'r', 'utf-8') as source:
  18. content = parser.convert(source.read())
  19. return content, hasattr(parser, 'Meta') and parser.Meta or None
  20. En combinant les deux, on obtient la boucle suivante :
  21. :::python
  22. for file_path in each_markdown_from(POSTS_PATH):
  23. content, metadata = parse_markdown(file_path)
  24. Dans [un prochain épisode](/david/stream/2015/02/12/), on verra comment utiliser les `namedtuple`s à bon escient.