Example #1
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 #2
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 #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 run_pdflatex(context, outputfilename, overwrite=True):
    if 'textemplate' not in context:
        context['textemplate'] = "text-image-quer.tex"
    texenv = Environment(
        loader=PackageLoader("schilder", config.textemplatedir))
    texenv.variable_start_string = "${"
    texenv.variable_end_string = "}"
    texenv.block_start_string = "${{{{{"
    texenv.block_end_string = "}}}}}"
    template = texenv.get_template(context['textemplate'])
    #if not overwrite and os.path.isfile(outputfilename) and os.path.getmtime(template.filepath) < os.path.getmtime(outputfilename):
    #    return
    if context['markup'] == 'rst':
        context['text'] = publish_parts(context['text'],
                                        writer_name='latex')['body']
        #context['headline'] = publish_parts(context['headline'], writer_name='latex')['body']
    tmpdir = tempfile.mkdtemp(dir=config.tmpdir)
    if 'img' in context and context['img'] and context['img'] != '__none':
        try:
            shutil.copy(os.path.join(config.imagedir, context['img']),
                        os.path.join(tmpdir, context['img']))
        except:
            raise IOError("COULD NOT COPY")
    else:
        # print "MEH No image"
        pass
    tmptexfile = os.path.join(tmpdir, 'output.tex')
    tmppdffile = os.path.join(tmpdir, 'output.pdf')
    with open(tmptexfile, 'w') as texfile:
        texfile.write(template.render(form=context))
    os.symlink(config.texsupportdir, os.path.join(tmpdir, 'support'))
    try:
        texlog = sp.check_output(['pdflatex', '--halt-on-error', tmptexfile],
                                 stderr=sp.STDOUT,
                                 cwd=tmpdir,
                                 universal_newlines=True)
    except sp.CalledProcessError as e:
        if overwrite:
            try:
                flash(
                    Markup("<p>PDFLaTeX Output:</p><pre>%s</pre>" % e.output),
                    'log')
            except:
                print((e.output))
        raise SyntaxWarning("PDFLaTeX bailed out")
    if overwrite:
        try:
            flash(Markup("<p>PDFLaTeX Output:</p><pre>%s</pre>" % texlog),
                  'log')
        except:
            print(texlog)
    shutil.copy(tmppdffile, outputfilename)
    shutil.rmtree(tmpdir)
Example #9
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 #10
0
 def long(self):
     from os.path import dirname, join
     from jinja2 import Environment, FileSystemLoader
     template_paths = [dirname(__file__)]
     if self.project:
         template_paths.insert(0, join(self.project.path, ".smt"))
     env = Environment(loader=FileSystemLoader(template_paths))
     env.block_start_string = '{%'
     env.block_end_string = '%}'
     env.variable_start_string = '@'
     env.variable_end_string = '@'
     env.filters['human_readable_duration'] = human_readable_duration
     env.filters['escape_tex'] = LaTeXFormatter._escape_tex
     template = env.get_template('latex_template.tex')
     return template.render(records=self.records,
                            project=self.project,
                            paper_size='a4paper')
Example #11
0
        for v, e in zip(values, err):
            vv, ee = str(ufloat(v, e)).split('+/-')
            v_pre, v_post = vv.split('.')
            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:
Example #12
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
Example #13
0
        error = 0
        for v, e in zip(values, err):
            vv, ee = str(ufloat(v, e)).split('+/-')
            v_pre, v_post = vv.split('.')
            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:
Example #14
0
            os.path.dirname(os.path.realpath(__file__))+'/../templates/skeleton/',
            ]),
        extensions=['jinja2.ext.loopcontrols']
        )


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
Example #15
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 #16
0
        participants.extend(_data)
    else:
        data['talks'][name] = _data
        participants.append(_data['Authors'][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]
Example #17
0
if not os.path.exists(resource_path): os.makedirs(resource_path)
schema_path = os.path.join(os.path.dirname(__file__), "../..", '{{cookiecutter.app_name}}', "api", 'schemas')
if not os.path.exists(schema_path): os.makedirs(schema_path)
tmp_path = os.path.join(os.path.dirname(__file__), "../..", 'tmp', 'api')
if not os.path.exists(tmp_path): os.makedirs(tmp_path)
tb_prefix = ['{{cookiecutter.app_name}}_', 'ti_', 'tu_', 'ts_', 'tt_', 'tl_', 'tm_', 'ta_']
jinjia_env = Environment(
    loader=PackageLoader('{{cookiecutter.app_name}}', 'templates'),
    autoescape=True)
jinjia_env.filters['to_camel_case'] = to_camel_case
jinjia_env.filters['to_pascal_case'] = to_pascal_case
jinjia_env.filters['dbtype_transfer'] = dbtype_transfer
jinjia_env.filters['factoryboy_gen'] = factoryboy_gen
jinjia_env.variable_start_string = "[["
jinjia_env.variable_end_string = "]]"
jinjia_env.block_start_string = "{[%"
jinjia_env.block_end_string = "%]}"


def start():
    try:
        db_url = os.getenv('DATABASE_URI')
        db.reflect()
        choose_title1 = '请选择生成的代码模块:'
        choose_options1 = ['api', 'model']
        choose_selected1 = pick(choose_options1, choose_title1, multi_select=True, min_selection_count=1)
        choose_selected1 = list(map(lambda x: x[0], choose_selected1)) if choose_selected1 else None
        all_table = [{"tb_name": table_obj.name, "tb_obj": table_obj} for table_obj in db.get_tables_for_bind()]
        all_table.sort(key=lambda x: x.get('tb_name'))
        geterate_all_title = '请选择是否生成所有表:'
        geterate_all_options = [False, True]
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)