Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

customising Pandoc's HTML output with CSS or a template

Tags:

haskell

pandoc

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?

like image 652
daf Avatar asked Jun 20 '13 20:06

daf


People also ask

Where are Pandoc templates?

The default LaTeX template of Pandoc can be found at https://github.com/jgm/pandoc/tree/master/data/templates (named default.

Can Pandoc convert HTML to markdown?

Pandoc can convert between numerous markup and word processing formats, including, but not limited to, various flavors of Markdown, HTML, LaTeX and Word docx.

How do I use a HTML template?

The <template> tag is used as a container to hold some HTML content hidden from the user when the page loads. The content inside <template> can be rendered later with a JavaScript. You can use the <template> tag if you have some HTML code you want to use over and over again, but not until you ask for it.


2 Answers

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 "..."
like image 87
daf Avatar answered Sep 29 '22 17:09

daf


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.

like image 39
Clément Avatar answered Sep 29 '22 17:09

Clément