summaryrefslogtreecommitdiff
path: root/panfry/templater.py
blob: c420a12ed7f43cd52aa248f6cc74f3208003ec30 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from jinja2 import Environment, FileSystemLoader


class Templater:
    ''' Pandoc Template generator.
    Creates a template suitible for passing to pandoc for html generation.

    The most prominent feature is adding the custom table of contents
    navigator that navigates accross muliple html pages.

    The generator references a jinja2 template file called html5.template
    located either in the directory 'templates' under the source path,
    or in the directory passed as an option.
    '''
    def __init__(self, path):
        self.templates_path = path
        self.j2 = Environment(loader=FileSystemLoader(self.templates_path),
                              line_statement_prefix='#')

    def page_template(self, doc, page):
        '''
        Returns a new page template for use by pandoc.

        Arguments:
        - doc: Panfry.Document.
        - page: Panfry.Page from Panfry.Document to generate template for.
        '''
        options = dict(toc=doc.toc_links)
        options['page'] = unicode(page.htmlfile, "utf8")
        options['pdf'] = unicode(doc.pdf_filename)
        options['prev'] = u''
        options['next'] = u''
        prevpage = doc.prev_page(page)
        nextpage = doc.next_page(page)
        if prevpage:
            options['prev'] = unicode(prevpage.htmlfile, "utf8")
        if nextpage:
            options['next'] = unicode(nextpage.htmlfile, "utf8")

        template = self.j2.get_template('html5.template')

        return template.render(options=options).encode('utf-8')