Example #1
0
def write_template(run, template_file, logo_file):

    template_file = path.abspath(path.realpath(template_file))
    template_dir = path.dirname(template_file)
    # spawn environment and create output directory
    env = Environment(loader=FileSystemLoader(template_dir))

    # change delimiters since LaTeX may use "{{", "{%", or "{#"
    env.block_start_string = "((*"
    env.block_end_string = "*))"
    env.variable_start_string = "((("
    env.variable_end_string = ")))"
    env.comment_start_string = "((="
    env.comment_end_string = "=))"

    # trim all block-related whitespaces
    env.trim_blocks = True
    env.lstrip_blocks = True

    # put in out filter functions
    env.filters["nice_int"] = nice_int
    env.filters["nice_flt"] = nice_flt
    env.filters["float2nice_pct"] = float2nice_pct
    env.filters["basename"] = path.basename

    # write tex template for pdflatex
    jinja_template = env.get_template(path.basename(template_file))
    run.logo = logo_file
    render_vars = {
        "run": run,
    }
    rendered = jinja_template.render(**render_vars)

    print(rendered, file=sys.stdout)
Example #2
0
def render(template_path, data, extensions, strict=False, opts={}):
    from jinja2 import Environment, FileSystemLoader, StrictUndefined

    env = Environment(
        loader=FileSystemLoader(os.path.dirname(template_path)),
        extensions=extensions,
        keep_trailing_newline=True,
    )
    if strict:
        env.undefined = StrictUndefined
    if opts.block_start_string:
        env.block_start_string = opts.block_start_string
    if opts.block_end_string:
        env.block_end_string = opts.block_end_string
    if opts.variable_start_string:
        env.variable_start_string = opts.variable_start_string
    if opts.variable_end_string:
        env.variable_end_string = opts.variable_end_string
    if opts.comment_start_string:
        env.comment_start_string = opts.comment_start_string
    if opts.comment_end_string:
        env.comment_end_string = opts.comment_end_string

    # Add environ global
    env.globals["environ"] = lambda key: force_text(os.environ.get(key))
    env.globals["get_context"] = lambda: data

    return env.get_template(os.path.basename(template_path)).render(data)
Example #3
0
    def make_file(self):

        texenv = Environment(loader=TeXLoader(self.home))
        texenv.block_start_string = '((*'
        texenv.block_end_string = '*))'
        texenv.variable_start_string = '((('
        texenv.variable_end_string = ')))'
        texenv.comment_start_string = '((='
        texenv.comment_end_string = '=))'
        texenv.filters['escape_tex'] = escape_tex

        if "template" not in self.variables:
            self.variables["template"] = self.default_template

        template_file = self.template_dir + \
            '/' + self.variables["template"] + '.tex'

        if not exists(template_file):
            template_file = join(
                dirname(realpath(__file__)),
                self.variables["template"] + '.tex')

        template = texenv.get_template(template_file)

        f = open(self.temp_file, "w")
        f.write(template.render(self.variables))
        f.close()

        print("Temporary LaTeX file created ({})\n---".format(self.temp_file))
Example #4
0
def makepdf(destdir, pdfname, template, debug=False, attach=None, **data):  #pylint: disable=R0915,R0914
    "Genera file PDF da template LaTeX"
    path, fname = os.path.split(template)
    env = Environment(loader=FileSystemLoader(path))
    tempdir = os.path.join(destdir, 'tmp')
    cleantempdir(tempdir)
    os.mkdir(tempdir)
    env.block_start_string = '((*'
    env.block_end_string = '*))'
    env.variable_start_string = '((('
    env.variable_end_string = ')))'
    env.comment_start_string = '((='
    env.comment_end_string = '=))'
    template = env.get_template(fname)
    tname = tempnam(tempdir)
    tmplatex = tname+'.tex'
    tmppdf = tname+'.pdf'
    tpath, tname = os.path.split(tname)
    if debug:
        logging.debug("Template: %s", template.name)

    atcs = []
    if attach:
        for atch in attach:
            logging.debug('Processing attachment: %s', atch)
            atcs.append(SplittedAttachment(tempdir, atch, debug))

    newdata = sanitize(data)
    with open(tmplatex, encoding='utf-8', mode='w') as fpt:
        tex = template.render(**newdata)
        fpt.write(tex)
    if atcs:
        do_attachments(tmplatex, atcs)
    cmd = [PDFLATEX.cmd]
    if BATCHMODE.on:
        cmd.extend(['-interaction', 'batchmode'])
    cmd.extend(['-output-directory', tpath, tmplatex])
    logging.info('LaTeX cmd: %s', ' '.join(cmd))
    subp = subprocess.Popen(cmd, stderr=subprocess.PIPE)
    errors = subp.stderr.readlines()
    for err in errors:
        logging.error("LaTeX stderr: %s", err.strip())
    pdffile = os.path.join(destdir, pdfname)
    if not os.path.exists(tmppdf):
        logging.error("LaTeX did not generate temp file: %s", tmppdf)
    logging.debug("Renaming %s to %s", tmppdf, pdffile)
    try:
        os.rename(tmppdf, pdffile)
        os.chmod(pdffile, 0o600)
        ret = True
    except Exception as excp:  #pylint: disable=W0703
        ret = True
        logging.error("renaming %s to %s [%s]", tmppdf, pdffile, str(excp))
    if  debug:
        logging.debug("Temp. dir not removed: %s", tempdir)
    else:
        cleantempdir(tempdir)
    return ret
Example #5
0
def make_tex_env(template_dir):
    loader = FileSystemLoader(template_dir)
    texenv = Environment(loader=loader)
    texenv.block_start_string = '((*'
    texenv.block_end_string = '*))'
    texenv.variable_start_string = '((('
    texenv.variable_end_string = ')))'
    texenv.comment_start_string = '((='
    texenv.comment_end_string = '=))'
    texenv.filters['escape_tex'] = escape_tex
    return texenv
def get_jinja_env(template_data):
    env = Environment(loader=PackageLoader('cvbuilder', 'templates'))

    # Change start/end strings if necessary
    # For TEX templates, this is _always_ necessary
    if "strings" in template_data or "tex" in template_data["language"]:
        try:
            strings = template_data["strings"]
        except KeyError:
            print "\nWarning: Start/end strings are necessary in TEX templates"
            exit()

        if "variable_start" in strings:
            env.variable_start_string = strings["variable_start"]
        elif "variable_begin" in strings:
            env.variable_start_string = strings["variable_begin"]
        if "variable_end"   in strings:
            env.variable_end_string   = strings["variable_end"]

        if "block_start" in strings:
            env.block_start_string = strings["block_start"]
        elif "block_begin" in strings:
            env.block_start_string = strings["block_begin"]
        if "block_end"   in strings:
            env.block_end_string   = strings["block_end"]

        if "comment_start" in strings:
            env.comment_start_string = strings["comment_start"]
        elif "comment_begin" in strings:
            env.comment_start_string = strings["comment_begin"]
        if "comment_end"   in strings:
            env.comment_end_string   = strings["comment_end"]

    if "html" in template_data["language"]:
        env.autoescape = True

    env.filters['datetimeformat'] = datetimeformat
    env.filters['escape_tex']     = escape_tex
    env.filters['bibtex']         = bibtex

    return env
Example #7
0
def get_tex_tpl(path):
    texenv = Environment(loader=FileSystemLoader(os.getcwd()))
    texenv.block_start_string = '((*'
    texenv.block_end_string = '*))'
    texenv.variable_start_string = '((('
    texenv.variable_end_string = ')))'
    texenv.comment_start_string = '((='
    texenv.comment_end_string = '=))'
    texenv.trim_blocks = True
    texenv.lstrip_blocks = True

    return texenv.get_template(path)
Example #8
0
def get_env():
    env = Environment(loader=FileSystemLoader('.'))
    env.block_start_string = '((*'
    env.block_end_string = '*))'
    env.variable_start_string = '((('
    env.variable_end_string = ')))'
    env.comment_start_string = '((='
    env.comment_end_string = '=))'
    env.filters['escape'] = escape_tex
    env.filters['medium'] = translate_medium
    env.filters['strip_extension'] = strip_extension
    env.filters['f'] = format_float
    env.filters['percent'] = percent
    return env
Example #9
0
def _init_template_env(templates_dir=None):
    """
    Initialize the jinja2 templating environment using the templates in the
    given directory.
    """
    if not templates_dir:
        templates_dir = DEFAULT_TEMPLATES_DIR

    env = Environment(loader=FileSystemLoader(templates_dir),
                      autoescape=False,
                      undefined=StrictUndefined)
    env.filters['datetimefilter'] = _datetimefilter

    # Avoid problems with bash syntax ${#...}
    env.comment_start_string = '{##'

    return env
Example #10
0
def include_mustache(context, template_path, scriptag=True, **kwargs):
    env = Environment(loader=context.environment.loader, trim_blocks=True)
    env.variable_start_string = '{{{{'
    env.variable_end_string = '}}}}'
    env.comment_start_string = '{{{#'
    env.comment_end_string = '#}}}'
    #loader = env.loader
    #template, filename, uptodate= loader.get_source(env, template_path)
    template_context = dict(context.get_all())
    template_context.update(**kwargs)
    template = env.get_template(template_path, globals=template_context)
    template = template.render()
    stagid = os.path.splitext(template_path)[0].replace('/', '_')
    if scriptag:
        template = '<script id="%s" class="mustache-template" type="text/template">\n%s\n</script>'%(stagid, template)
    if context.eval_ctx.autoescape:
        template = Markup(template)
    return template
Example #11
0
def render_mustache(context, template_path, **kwargs):
    env = Environment(loader=context.environment.loader, trim_blocks=True)
    env.variable_start_string = '{{{{'
    env.variable_end_string = '}}}}'
    env.comment_start_string = '{{{#'
    env.comment_end_string = '#}}}'
    #loader = env.loader
    #template, filename, uptodate= loader.get_source(env, template_path)
    template_context = dict(context.get_all())
    template_context.update(**kwargs)
    template = env.get_template(template_path, globals=template_context)
    template = template.render()
    view = dict(context.get_all())
    view.update(**kwargs)
    result = pystache.render(template, view)
    if context.eval_ctx.autoescape:
        result = Markup(result)
    return result
Example #12
0
def render_mustache(context, template_path, **kwargs):
    env = Environment(loader=context.environment.loader, trim_blocks=True)
    env.variable_start_string = '{{{{'
    env.variable_end_string = '}}}}'
    env.comment_start_string = '{{{#'
    env.comment_end_string = '#}}}'
    #loader = env.loader
    #template, filename, uptodate= loader.get_source(env, template_path)
    template_context = dict(context.get_all())
    template_context.update(**kwargs)
    template = env.get_template(template_path, globals=template_context)
    template = template.render()
    view = dict(context.get_all())
    view.update(**kwargs)
    result = pystache.render(template, view)
    if context.eval_ctx.autoescape:
        result = Markup(result)
    return result
Example #13
0
def include_mustache(context, template_path, scriptag=True, **kwargs):
    env = Environment(loader=context.environment.loader, trim_blocks=True)
    env.variable_start_string = '{{{{'
    env.variable_end_string = '}}}}'
    env.comment_start_string = '{{{#'
    env.comment_end_string = '#}}}'
    #loader = env.loader
    #template, filename, uptodate= loader.get_source(env, template_path)
    template_context = dict(context.get_all())
    template_context.update(**kwargs)
    template = env.get_template(template_path, globals=template_context)
    template = template.render()
    stagid = os.path.splitext(template_path)[0].replace('/', '_')
    if scriptag:
        template = '<script id="%s" class="mustache-template" type="text/template">\n%s\n</script>' % (
            stagid, template)
    if context.eval_ctx.autoescape:
        template = Markup(template)
    return template
Example #14
0
            e_pre, e_post = ee.split('.')

            if len(v_pre) > before:
                before = len(v_pre)
            if len(v_post) > after:
                after = len(v_post)
            if len(e_post) > error:
                error = len(e_post)

            return "{}.{}({})".format(before, after, error)

env.block_start_string = '#<'
env.block_end_string = '>#'
env.variable_start_string = '<<'
env.variable_end_string = '>>'
env.comment_start_string = '#='
env.comment_end_string = '=#'
env.filters['escape_tex'] = escape_tex
env.filters['si'] = si
paper = sys.argv[-1]
template = env.get_template(paper)

db = dict()

scripts = sys.argv[1:-1]
for scr in scripts:
    with open(scr) as f:
        code = compile(f.read(), 'test.py', 'exec')
        exec(code, globals(), locals())

db = locals()
Example #15
0
texenv = Environment(
        loader=FileSystemLoader([
            os.path.dirname(os.path.realpath(__file__))+'/../templates/tex/',
            os.path.dirname(os.path.realpath(__file__))+'/../templates/skeleton/tex/',
            ]),
        extensions=['jinja2.ext.loopcontrols']
        )


texenv.block_start_string = '((*'
texenv.block_end_string = '*))'

texenv.variable_start_string = '((('
texenv.variable_end_string = ')))'

texenv.comment_start_string = '((='
texenv.comment_end_string = '=))'

texenv.filters['escape_tex'] = escape_tex

#-----------------------------------------------------------------------------
# Class declarations
#-----------------------------------------------------------------------------
class ConversionException(Exception):
    pass

class ConverterTemplate(Configurable):
    """ A Jinja2 base converter templates

    Preprocess the ipynb files, feed it throug jinja templates,
    and spit an converted files and a data object with other data
Example #16
0
from pelican import signals
from laconia import ThingFactory
from rdflib import Graph, RDFS, OWL, Namespace, RDF
from jinja2 import Environment, PackageLoader
from jinja2 import tests


env_md = Environment(loader=PackageLoader('cv', 'templates'))
template_md = env_md.get_template('template.md')

env_tex = Environment(loader=PackageLoader('cv', 'templates'))
env_tex.block_start_string = '((*'
env_tex.block_end_string = '*))'
env_tex.variable_start_string = '((('
env_tex.variable_end_string = ')))'
env_tex.comment_start_string = '((='
env_tex.comment_end_string = '=))'
template_latex = env_tex.get_template('template.tex')

CV = Namespace('http://rdfs.org/resume-rdf/cv.rdfs#')


def render(_sender):
    g = Graph()
    # TODO: make configurable
    g.parse('content/extra/cv.ttl', format='turtle')

    # TODO: make configurable
    cv = ThingFactory(g)('http://rossfenning.co.uk/cv/#cv')

    skills = {
Example #17
0
            if len(v_pre) > before:
                before = len(v_pre)
            if len(v_post) > after:
                after = len(v_post)
            if len(e_post) > error:
                error = len(e_post)

            return "{}.{}({})".format(before, after, error)


env.block_start_string = '#<'
env.block_end_string = '>#'
env.variable_start_string = '<<'
env.variable_end_string = '>>'
env.comment_start_string = '#='
env.comment_end_string = '=#'
env.filters['escape_tex'] = escape_tex
env.filters['si'] = si
paper = sys.argv[-1]
template = env.get_template(paper)

db = dict()

scripts = sys.argv[1:-1]
for scr in scripts:
    with open(scr) as f:
        code = compile(f.read(), 'test.py', 'exec')
        exec(code, globals(), locals())

db = locals()
Example #18
0
from jinja2 import Environment, FileSystemLoader
import re

LATEX_SUBS = (
    (re.compile(r"\\"), r"\\textbackslash"),
    (re.compile(r"([{}_#%&$])"), r"\\\1"),
    (re.compile(r"~"), r"\~{}"),
    (re.compile(r"\^"), r"\^{}"),
    (re.compile(r'"'), r"''"),
    (re.compile(r"\.\.\.+"), r"\\ldots"),
)


def escape_tex(value):
    newval = value
    for pattern, replacement in LATEX_SUBS:
        newval = pattern.sub(replacement, newval)
    return newval


# Config scripts are called from the main directory.
# TODO: Would be nice to remove this dependancy.
texenv = Environment(loader=FileSystemLoader(".config/templates"))
texenv.block_start_string = "((*"
texenv.block_end_string = "*))"
texenv.variable_start_string = "((("
texenv.variable_end_string = ")))"
texenv.comment_start_string = "((="
texenv.comment_end_string = "=))"
texenv.filters["escape_tex"] = escape_tex
yam = argv[1]
tmp = argv[2]

TEXFILE = False
if tmp.endswith(".tex.jinja"):
    TEXFILE = True

with open(yam) as fd:
    yamtext = fd.read()
    #if TEXFILE:
    #    yamtext = yamtext.replace(r'&', r'\\&')
    #    yamtext = yamtext.replace(r'_', r'\\_')
    #    yamtext = yamtext.replace(r'%', r'\\%')
    #    yamtext = yamtext.replace(r'$', r'\\$')
    #    yamtext = yamtext.replace(r'?', r'\\?')
    data = load(yamtext)

with open(tmp) as fd:
    template = fd.read()

env = Environment(lstrip_blocks=True, trim_blocks=True)
if TEXFILE:
    env.block_start_string = "[[%"
    env.block_end_string = "%]]"
    env.variable_start_string = "[["
    env.variable_end_string = "]]"
    env.comment_start_string = "[[="
    env.comment_end_string = "=]]"
render = env.from_string(template)
print render.render(data)
Example #20
0
data['participants'] = participants

# get template from command line
tmp = argv[2]
with open(tmp) as fd:
    template = fd.read()

# set parameters
env = Environment(lstrip_blocks=True, trim_blocks=True)
if tmp.endswith("tex.jinja"):
    env.block_start_string = "[[%"
    env.block_end_string = "%]]"
    env.variable_start_string = "[["
    env.variable_end_string = "]]"
    env.comment_start_string = "[[="
    env.comment_end_string = "=]]"


# custom filter
def timeformat(mins):
    return '{}:{:02d}'.format(mins // 60, mins % 60)


def readtime(string):
    n = list(map(int, string.split(':')))
    return n[0] * 60 + n[1]


def update_time(times, event, lenghts, quiet=False):
    if 'start' in event.keys():