7

I have a Happstack program that dynamically converts Markdown documents to HTML using Text.Pandoc:

import qualified Text.Pandoc as Pandoc
...
    return $ toResponse $ Pandoc.writeHtml Pandoc.def contents

I.e. Pandoc is returning a Text.Blaze.Html.Html value. (This has a ToMessage instance which means it can be used as a response to a request.)

How do I insert a custom CSS stylesheet into Pandoc's output? What if I want to customise the HTML e.g. by wrapping the <body> contents with some other elements?

daf
  • 5,085
  • 4
  • 31
  • 34

3 Answers3

8

When Pandoc's "standalone mode" option is enabled, it uses a template to format the output. The template and its substitions variables can be set in the writerTemplate and writerVariables members of WriterOptions.

The command line tool has a default set of template it uses. You can see the default template for a format using e.g. pandoc -D html.

When using the library, the default is to use an empty template. You can get the default template programmatically using getDefaultTemplate.

Here's some example code:

import Text.Blaze.Html.Renderer.String
import Text.Pandoc

getHtmlOpts = do
    template <- either (error . show) id
        `fmap` getDefaultTemplate Nothing "html"
    return $ def
        { writerStandalone = True
        , writerTemplate = template
        , writerVariables = [
            ("css", "/path/to/style.css"),
            ("header-includes",
             "<style>p { background-color: magenta; }</style>")]
        }

main = do
    opts <- getHtmlOpts
    putStrLn $ renderHtml $ writeHtml opts $ readMarkdown def "..."
daf
  • 5,085
  • 4
  • 31
  • 34
  • I was fighting the

    block, since I don't want to modify my markdown files, but still want to add the element properly... using `pandoc -D html > template.html` and then modifying the template to my taste (mainly adding `style="display:none"` to the `title-block-header` element, and compiling with `pandoc -s --template ./template.html --metadata title="$title" "$oldname" -o "$newname"` solved all my drama.

    – mazunki Jul 22 '21 at 22:02
4

You can also write your own template, call it for instance template.html and use the --template template.html option when calling pandoc from the command-line.

The documentation is at https://pandoc.org/MANUAL.html#templates, and the default template (for inspiration) is at https://raw.githubusercontent.com/jgm/pandoc-templates/master/default.html5.

Clément
  • 2,358
  • 28
  • 32
1

Pandoc, when run from the command line, takes some arguments that allow you to insert something into the <head> tag (-H), before content (-B) and after content (-A). I don't know about Happstack, but surely there must be a way to pass these parameters to Pandoc.writeHtml