This repository has been archived on 2023-03-26. You can view files and clone it, but cannot push or open issues or pull requests.
md-pdf/md_pdf/build/template.py

53 lines
1.4 KiB
Python
Raw Normal View History

2017-05-10 17:22:55 +01:00
from jinja2 import Template
from bs4 import BeautifulSoup
import os
import logging
logger = logging.getLogger(__file__)
2017-05-10 17:41:49 +01:00
def fix_references_title(content, config):
2017-05-10 17:22:55 +01:00
logger.debug("Adding Reference Title...")
soup = BeautifulSoup(content, 'html.parser')
reference_element = soup.find('div', class_='references')
if reference_element is not None:
title = soup.new_tag('h1')
2017-05-10 20:52:00 +01:00
title['class'] = 'references-title'
2017-05-10 17:22:55 +01:00
title.string = "References"
reference_element.insert_before(title)
return soup.prettify()
def add_base_tag(doc, config):
logger.debug("Adding Base Tag...")
soup = BeautifulSoup(doc, 'html.parser')
2017-05-10 21:42:03 +01:00
for img in soup.findAll('img'):
2017-05-11 13:19:14 +01:00
abs_path = os.path.abspath(img['src'])
if os.path.isfile(abs_path):
img['src'] = abs_path
2017-05-10 17:22:55 +01:00
return soup.prettify()
2017-05-10 18:14:30 +01:00
def add_body_class(doc, config):
logger.debug("Adding Body Class...")
soup = BeautifulSoup(doc, 'html.parser')
soup.body['class'] = 'content'
return soup.prettify()
2017-05-10 17:22:55 +01:00
def render_template(html, config):
logger.debug("Rendering Template...")
template = Template(html)
return template.render(config)
def parse_template(doc, config):
2017-05-10 17:41:49 +01:00
parsed_doc = doc
for parser in [
fix_references_title,
add_base_tag,
2017-05-10 18:14:30 +01:00
add_body_class,
2017-05-10 17:41:49 +01:00
]:
parsed_doc = parser(parsed_doc, config)
2017-05-10 18:14:30 +01:00
return render_template(parsed_doc, config)