Package: md-to-html2
Convert Markdown to HTML using Jinja2 templatesThis converts a markdown file to a full HTML file by using a template.
Can be used to make small standalone HTML documents, or larger multi-page sites.
The default templates are:simple: A simple one layout usingBootstrap.navright: Likesimple, but includes a navigation column on the right for medium screens.
(See a demohere.)revealjs: ARevealJSpresentation. (See a demohere.)ALightGalleryslideshow. (See a demohere.)
(This script can also resize your original images and create thumbnails / web versions for your slideshow. See the demo for instructions.)InstallationUsing pip:Runpip install "md-to-html2[resize,codehilite]".
(Note the extra2; the namemd-to-htmlwas already used on PyPi 🙄.)On Arch Linux:Installmd-to-html2from theAUReithermanually, or using ahelper.Installing manuallyClone the repositoryhttps://codeberg.org/gi1242/md-to-html.gitCreate a symlink tosrc/md-to-htmlfrom somewhere in yourPATH.Install the required dependencies:python,python-frontmatter,python-jinja,python-markdown,python-pyxdg.Optionally install the optional dependencies:python-pillow(for resizing images),python-pygments(for syntax highlighting output).UsageOne page use caseJust runmd-to-html file.mdto producefile.html.
This is good for creating a simple webpage, RevealJS presentation, LightGallery slideshow.
Optionally choose template / set options in theYAML front matter.Multi-page use caseTo build more complicated sites, this script can do two the following:Recurse directories and create HTML files (either in the same location, or in a specified destination directory preserving the hierarchy).Resize images to create thumbnails / web-versions for your slideshows.Move JavaScript / CSS to a separate shared directory, instead of inlining them.Recurse through the destination directory, and purge all HTML files that don't correspond to markdown source files. (You can set exclude / preserve lists.)Run external commands you can use to copy static files (e.g. CSS / JS).To build a website, you may need a few other things.
This script doesn't do them because there are other tools that do them excellently.
For example:Copying static files, or uploading to your web server.
I usersyncfor this. (You can configure this script to runrsyncor any external command on successful completion using theexecoption in config files.)Automatically watch files and compile HTML when the source is changed.
I configured my editor (Neovim) to do this automatically every time a source file is changed (instructionshere).Automatically reload the HTML preview when the HTML is compiled.
I use alivereloadserver (instructionshere).ExampleLook insite-config.yamlfor an example that generatedthis siteCommand line optionsusage: md-to-html [-h] [-c CONFIG] [-d] [-f] [-F] [-n] [-q] [-R] [-r] [-s]
                  [-p PREVIEW] [-t THREADS] [-u] [-v]
                  [files ...]

Convert markdown files to HTML using Jinja2 templates

positional arguments:
  files                 Markdown (or YAML config) files

options:
  -h, --help            show this help message and exit
  -c CONFIG, --config CONFIG
                        Config file (YAML)
  -d, --delete-extra    Delete extra html files
  -f, --force           Render whether or not source is newer
  -F, --force-resize    Resize images whether or not source is newer
  -n, --no-exec         Don't run commands specified by 'exec'
  -q, --quiet           Suppress info messages
  -R, --no-recurse      Recurse subdirectories for *.md files
  -r, --resize-images   Resize images for slideshows
  -s, --show-extra      Show extra html files
  -p PREVIEW, --preview PREVIEW
                        Launch preview for output file (no output is
                        generated)
  -t THREADS, --threads THREADS
                        Number of threads. Use 0 (default) to let the system
                        decide automatically.
  -u, --update          Only render if source is newer
  -v, --verbose         Show debug messagesConfiguration (from YAML config files)In addition to config files supplied with-c, the following directories are searched for configuration.The directory this script was installed in/etc/xdg/md-to-html~/.config/md-to-htmlThe directory of the input file.Global options should be in aconfig.yamlfile.
The default options are:enable_mathjax:trueenable_codehilite:trueenable_jinja:falsejinja_prefix:'jinja'jinja_header:>{%- import 'lightgallery.j2' as LightGallery -%}template:simplestandalone:truetoc_depth:2-4encoding:utf-8base_url:''# Include trailing slashshared_dir:shared/md-to-htmlabsolute_links:falseupdate:falseexclude_dirs:-.git-__pycache__-templates-reveal.jsexclude_files:[]protect_dirs:-reveal.js-/shared/md-to-htmlprotect_files:[]base_dir: Base of the source directory hierarchy. Source file outside this directory will raise an exception. (Default..) It is treated as a relative path from the file it was defined in, so thatbase_dir: .works as expected.dst_dir: All output goes in this directory, preserving the directory hierarchy up tobase_dir.
That isbase_dir/path/file.mdbecomesdst_dir/path/file.html.
It is treated as a relative path from the file it was defined in.shared_dir: For non-standalone documents, put CSS / JS here.standalone: If true, all CSS / JS is included inline.base_url: Base URL of the target site. Shared files should accessible atbase_url/shared_dir.
If empty, then relative paths will be used for shared files.dst_file: Destination file name (relative todst_dir). If unspecified, use the source file name with.htmlextension.exclude_files/exlcude_dirs: List of glob patterns of source files / directories to ignore when recursing through directories. (Values are appended to existing values; to clear the list use!!resetas the first entry.)protect_files/protect_dirs: List of glob patterns of destination files / directories to protect from deletion. When-dis used, all HTML files in the destination directory that do not correspond to source markdown files are deleted.protect_files/protect_dirscan be used to protect some of these files from deletion. (Values are appended to existing values; to clear the list use!!resetas the first entry.)sources: List of source files / directories to convert to HTML / recurse into. (Ignored if files are present on command line.)update: Only compile source if it is newer than the target HTML (overridden by-u/-fon command line)exec: Commands to run if all files are processed without error (must be defined in a YAML config file specified with-c)
Useful to startrsyncto transfer static files.
Multiple commands can be given if separated by newlines.
All commands are passed through a shell, and run inbase_dir.Configuration (from YAML front matter)All metadata, including the template name, can also be specified asYAMLfront matter surrounded by---:---
template: simple
encoding: utf-8
enable_jinja: true
---
Markdown content starts here.Markdown Syntax and ExtensionsWe usepython-markdownto render the HTML, with the following extensions enabled:Extra: A compilation of various Python-Markdown extensions that (mostly) imitates PHP Markdown Extra.
The supported extensions include: Abbreviations, Attribute Lists, Definition Lists, Fenced Code Blocks, Footnotes, Tables, Markdown in HTML.Sane Lists: The Sane Lists extension alters the behavior of the Markdown List syntax to be less surprising.SmartyPants: The SmartyPants extension converts ASCII dashes, quotes and ellipses to their HTML entity equivalents.Table of Contents: The Table of Contents extension generates a Table of Contents from a Markdown document and adds it into the resulting HTML document. (Use it either in templates via{{toc}}or in markdown after settingenable_jinja: true.)Strikethrough:Producestrike throughtext using~~text~~CodeHilite: The CodeHilite extension adds code/syntax highlighting to standard Python-Markdown code blocks usingPygments. (Disable it withenable_codehilite: false)Wiki Links:To use[[link.html|label]]syntax (and provide warnings if the link is to a local find and isn't found.Math: Render math usingMathJax.
For example:
$\displaystyle
f(z) = \frac{1}{2\pi i} \oint_{\abs{z - \zeta} = r} \frac{f(\zeta)}{z - \zeta} , d\zeta ,.
$Jinja2expressions ifenable_jinjais true (default is false).MathJax Macros and optionsA fewMathJaxoptions and LaTex macros are defined in thesimple.j2template.
To add your own macros or change the mathjax configuration, you have a few options:For new macros in one document use this at the start of the file:$
   \newcommand{\mymacro}{expansion}
   ...
 $For per document configuration changes use themathjax_configYAML metadata.:::yaml
 ---
 mathjax_config: |
   MathJax.tex.tags = 'ams'
   MathJax.tex.macros = {
     ...MathJax.tex.macros,
     sign: '\\operatorname{sign}',
     abs: [ '#1\\lvert#2#1\\rvert', 2, '' ]
   }
 ---The
contents ofmathjax_configare treated as JavaScript and included right after theMathJaxconfiguration object is defined.
You can, for instance, also define (or undefine) macros usingMathJax.tex.macros.
(If you put this inconfig.yaml, then it will be used for all files in that directory.)For more global settings, you can extend the template and override  themathjaxblock (look attests/templates/custom.j2for an example).WikiLinksUse[[file.html|label]]to generate a link tofile.htmlwith labellabel.
To use the file name as the label, just use[[file.html]]Link to files which don't exist produce a warning.[[/absolute/path]]links tobase_url/absolute/path.Ifabsolute_linksis set, then all wiki-links are converted to absolute links usingbase_url/absolute/path.Using Jinja2 commands in the markdown file.By defaultJinja2expressions are only available in templates, and not in the markdown file.
If you want to use them, setenable_jinja=truein either the metadata or global configuration options.
For example::::markdown
---
title: Document tile
author: Author
template: simple
enable_jinja: true
user_flag: true
---

# {{title}}

*{{author}}, 2023-10-06*

You can use Jinja2 expressions: 1 + 1 = {{1 + 1}}.

{% if user_flag %}
You can set conditionals in metadata
{% else %}
and render content based on the values.
{% endif %}Note:enable_jinja=falseby default so invalid Jinja2 expressions don't surprise users.TemplatesA file is converted to HTML using aJinja2template.
Templates should be in thetemplatessubdirectory of one of the configuration folders, and should have a.j2extension.
A bare bones example of a template is::::jhtml
<!DOCTYPE html>
<html>
  <head><title>{{title}}</title></head>
  <body>{{content}}</body>
</html>All YAML metadata and global options are accessible as template variables.
The following additional variables are defined while processing:uses_math: True if math was detected when rendering the fileuses_codehilite: True if syntax highlighted code was detected when rendering the filetoc: HTML table of contents obtained from the filetitle: Contents of the first<h1>element, if not previously set.content: Document content after conversion from Markdown to HTMLExtensionsConvert the contents of thevarfrom markdown to HTML by{{var|markdown}}.Convert an arbitrary block of markdown to HTML using{% markdown %}... {% endmarkdown %}.Template specific optionsThere are various template specific options that can be set from YAML front matter (or config files).For instance, to add a style sheet, you can useend_head: <link href="..." rel="stylesheet" integrity="..." crossorigin="anonymous">Live PreviewsYou can have the web browser automatically reload the HTML preview every time you make a change.
Two ways of doing this are described inexamples/livereload/index.mdmd-to-htmlCopyright 2023, Gautam Iyer. MIT Licence.