build_a_blog: md convert reuse

This commit is contained in:
Collin Lefeber 2024-06-18 10:02:26 -04:00
parent a13727f381
commit 91fcf8036a
2 changed files with 12 additions and 8 deletions

15
main.py
View file

@ -12,6 +12,12 @@ from markdown.extensions.toc import TocExtension
destpath_re = re.compile(r'\.md$') destpath_re = re.compile(r'\.md$')
logging.basicConfig(encoding='utf-8', level=logging.INFO) logging.basicConfig(encoding='utf-8', level=logging.INFO)
md = markdown.Markdown(extensions=['extra', 'meta', TocExtension(anchorlink=True)])
def convert(text):
md.reset()
return md.convert(text)
def render_post(fpath): def render_post(fpath):
destpath = destpath_re.sub('.html', fpath) destpath = destpath_re.sub('.html', fpath)
logging.info("opening %s for parsing, dest %s", fpath, destpath) logging.info("opening %s for parsing, dest %s", fpath, destpath)
@ -20,15 +26,13 @@ def render_post(fpath):
logging.info("reading %s", fpath) logging.info("reading %s", fpath)
text = input_file.read() text = input_file.read()
md = markdown.Markdown(extensions = ['extra', 'meta', TocExtension(anchorlink=True)])
logging.info("parsing %s", fpath) logging.info("parsing %s", fpath)
out = md.convert(text) out = convert(text)
title = md.Meta.get('title')[0] title = md.Meta.get('title')[0]
date = md.Meta.get('date')[0] date = md.Meta.get('date')[0]
out = markdown.markdown('# ' + title) + out out = convert('# ' + title) + out
logging.info("writing to %s", destpath) logging.info("writing to %s", destpath)
render_template('index.html.tmpl', destpath, {'content': out, 'more_title': ' - ' + title}) render_template('index.html.tmpl', destpath, {'content': out, 'more_title': ' - ' + title})
@ -94,8 +98,7 @@ def rss_post_xml(post):
text = inf.read() text = inf.read()
md = markdown.Markdown(extensions=['extra', 'meta', 'toc']) converted = convert(text)
converted = md.convert(text)
pubdate = email.utils.format_datetime(datetime.datetime.fromisoformat(post['date'])) pubdate = email.utils.format_datetime(datetime.datetime.fromisoformat(post['date']))
subs = { subs = {

View file

@ -205,13 +205,14 @@ And pop open a python repl to see how this works.
Looks pretty nice! Looks pretty nice!
So first I will adjust the rendering function to prepend a So first I will adjust the rendering function to prepend a line:
```markdown ```markdown
# {title} # {title}
``` ```
Line just after we read the file and extract the metadata. This has to be done after the full document renders because the `meta` `python-markdown` extension extracts metadata and converts to html in one call.
```python ```python
def render_post(fpath): def render_post(fpath):