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)
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)
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))
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
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 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)
def get_template(template_name, context): try: template = fetch_template(template_name) if template: from jinja2 import Environment, PackageLoader env = Environment(loader=PackageLoader('main', 'templates')) env.variable_start_string = '<%=' env.variable_end_string = '%>' return env.from_string(template).render(context) except Exception as ex: print 'get_template %s' % ex
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)
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
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')
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
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
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
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
resource_path = os.path.join(os.path.dirname(__file__), "../..", '{{cookiecutter.app_name}}', "api", 'resources') 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 = '请选择是否生成所有表:'
def get_template(): texenv = Environment() # 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 texenv.filters['int_add_commas'] = int_add_commas template = texenv.from_string(r""" \documentclass[a4paper]{report} \usepackage{a4wide} \usepackage{fullpage} \usepackage{graphicx} \usepackage{microtype} \usepackage{color} \usepackage[T1]{fontenc} \usepackage{lmodern} \usepackage{booktabs} \heavyrulewidth=.13em \lightrulewidth=.08em \cmidrulewidth=.03em \usepackage{hyperref} \usepackage[table]{xcolor} \usepackage{longtable} \usepackage{pdflscape} \begin{document} \setlength\LTleft{0pt} \setlength\LTright{0pt} \setlength\tabcolsep{2pt} {% for gene, variants, coverage in objects %} \begin{landscape} \section*{((( gene.name ))) gene} Report for the ((( gene.name ))) gene, accession number {\tt ((( gene.accession|escape_tex )))}, at position {\tt ((( gene.chrom ))):((( gene.start|int_add_commas )))--((( gene.end|int_add_commas )))}. {% for table in tables %} \subsection*{sss((( table.title|escape_tex )))} {\sffamily \begin{longtable}{@{\extracolsep{\fill}}((( table.column_alignments )))@{}} \toprule {% for column in table %} ((( column.name|escape_tex ))){% if not loop.last %}&{% endif %} {% endfor %} \\ \midrule \endhead {% for variant in variants() -%} {% set call = variant.get_call(sample) %} {% if call.is_variant and table.matcher(variant, call) -%} {% for column in table -%} {% if column.type == 'exon' -%} E((( variant.exon ))) {% elif column.type == 'pos' %} ((( variant.exon_offset ))) {% elif column.type == 'abspos' %} \tt ((( variant.CHROM ))):((( variant.POS|int_add_commas ))) {% elif column.type == 'qual' %} ((( call.data.GQ ))) {% elif column.type == 'type' %} ((( variant.var_type ))) {% elif column.type == 'nc' %} {% if variant.get_base_change(call)|join(", ")|length > 10 %}\footnotesize{% endif %} {% if variant.get_base_change(call)|join(", ")|length > 15 %}\scriptsize{% endif %} ((( variant.REF ))) $\rightarrow$ ((( variant.get_base_change(call)|join(", ") ))) ({% if call.is_het %}het{% else %}hom{% endif %}) {% elif column.type == 'aac' %} {% if variant.aa_change_texts %} \tt ((( variant.aa_change_texts|join(", ")|escape_tex ))) {% else %} --- {% endif %} {% elif column.type == 'aaf' %} ((( variant.aaf ))) {% elif column.type == 'webref' %} {% if variant.ID -%} \href{http://ncbi.nlm.nih.gov/SNP/snp_ref.cgi?rs=((( variant.ID )))}{((( variant.ID )))} {% else %} --- {%- endif %} {% elif column.type == 'mutref' %} {% if variant.get_mut_ref(call)|length > 20 %}\footnotesize{% endif %} {% if variant.get_mut_ref(call)|length > 30 %}\scriptsize{% endif %} ((( variant.get_mut_ref(call)|escape_tex ))) {% elif column.type == 'eff' %} {% if not variant.effects -%} --- {% else %} {% for effect in variant.effects -%} {% if effect.impact == 'HIGH' %}\color{red}{% endif %} ((( effect.effect_type_text ))){% if not loop.last %}, {% endif %} {%- endfor %} {%- endif %} {%- endif %} {% if not loop.last %}&{% endif %} {%- endfor %} \\ {%- endif %} {%- endfor %} \bottomrule \end{longtable} } {% endfor %} \end{landscape} {% endfor %} \end{document} """) return template
def get_template(): texenv = Environment() # 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 texenv.filters['int_add_commas'] = int_add_commas template = texenv.from_string(r""" \documentclass[a4paper,landscape]{report} \usepackage{a4wide} \usepackage{fullpage} \usepackage{graphicx} \usepackage{microtype} \usepackage{color} \usepackage{tikz} \usepackage{pgfplots} \usetikzlibrary{datavisualization} \usetikzlibrary{pgfplots.groupplots} \usepackage{xcolor} \usepackage{colortbl} \usepackage[T1]{fontenc} \usepackage{lmodern} \usepackage{booktabs} \heavyrulewidth=.13em \lightrulewidth=.08em \cmidrulewidth=.03em \usepackage{hyperref} \usepackage{longtable} \usepackage{pdflscape} \begin{document} \setlength\LTleft{0pt} \setlength\LTright{0pt} \setlength\tabcolsep{2pt} {% for gene, exons, orf_exon_count, max_pileup, coverage_table_rows in objects %} % \begin{landscape} \section*{((( gene.name ))) gene} Report for the ((( gene.name ))) gene, accession number {\tt ((( gene.accession|escape_tex )))}, at position {\tt ((( gene.chrom ))):((( gene.start|int_add_commas )))--((( gene.end|int_add_commas )))}. Coverage within coding regions only. \\ \begin{tikzpicture} \path (0cm,0cm) -- (\textwidth, 0cm); \begin{groupplot}[ group style={ columns=((( orf_exon_count ))), vertical sep=0pt, ylabels at=edge left, xlabels at=edge bottom, yticklabels at=edge left, horizontal sep=0pt, }, extra y ticks={20}, extra y tick style={grid=major}, width=1/((( orf_exon_count )))*(\textwidth-2.0cm), height=3.0cm, ylabel=coverage, tickpos=left, xtick=\empty, ytick align=inside, xtick align=inside, scale only axis, ymin=0, ymax=((( max_pileup ))) ] {% for exon in exons %} {% if not exon.skip %} \nextgroupplot[xlabel=((( exon.name )))] \addplot [blue!{% if exon.coding %}80{% else %}70{% endif %}!black, fill=blue, fill opacity=0.2] coordinates {{% for point in exon.points %}( ((( point.0 ))),((( point.1 ))) ){% endfor %}} |- (axis cs:0,0) -- cycle; {% endif %} {% endfor %} \end{groupplot} \end{tikzpicture} {\sffamily \begin{longtable}{@{\extracolsep{\fill}}llrrrrrrrrrrrrrrrrrrrr@{}} {% for row in coverage_table_rows %} {% if loop.first %} \toprule & & \multicolumn{20}{c}{Exon} \\ {% else %} \midrule {% endif %} & {% for index, name in row %} & {% if not exons[index].skip %} {% if exons[index].min < 10 %} \cellcolor{red!25} {% elif exons[index].min < 20 %} \cellcolor{orange!25} {% elif exons[index].min < 30 %} \cellcolor{yellow!25} {% endif %} {% endif %} ((( name ))) {% endfor %}\\ \midrule {% if loop.first %} \endhead {% endif %} Coverage & avg. {% for index, name in row %} & {% if not exons[index].skip %} ((( '%d' | format(exons[index].mean) ))) {% else %} -- {% endif %} {% endfor %}\\ & min. {% for index, name in row %} & {% if not exons[index].skip %} ((( '%d' | format(exons[index].min) ))) {% else %} -- {% endif %} {% endfor %}\\ & max. {% for index, name in row %} & {% if not exons[index].skip %} ((( '%d' | format(exons[index].max) ))) {% else %} -- {% endif %} {% endfor %}\\ {% endfor %} \bottomrule \end{longtable} } % \end{landscape} \newpage {% endfor %} \end{document} """) return template
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: code = compile(f.read(), 'test.py', 'exec') exec(code, globals(), locals())
def get_template(): texenv = Environment() # 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 template = texenv.from_string(r""" \documentclass[11pt]{article} \usepackage{geometry} % See geometry.pdf to learn the layout options. There are lots. \geometry{letterpaper} % ... or a4paper or a5paper or ... \geometry{landscape} % Activate for for rotated page geometry %\usepackage[parfill]{parskip} % Activate to begin paragraphs with an empty line rather than an indent \usepackage{graphicx} \usepackage{amssymb} \usepackage{epstopdf} \usepackage{longtable, booktabs, multirow} \heavyrulewidth=.13em \lightrulewidth=.08em \cmidrulewidth=.03em \usepackage{xcolor} \usepackage{colortbl} \usepackage[small,bf,singlelinecheck=off]{caption} \begin{document} \setlength\LTleft{0pt} \setlength\LTright{0pt} \setlength\tabcolsep{2pt} \newpage { \sf \begin{longtable}{@{\extracolsep{\fill}} l{% for snp in snps %}c{% endfor %}@{\extracolsep{\fill}}} \toprule & {% for accession, reference in snps %} \rotatebox{85}{((( accession|escape_tex )))} {% if not loop.last %}&{% endif %} {% endfor %} \\ \cmidrule{2-((( snps|length + 1 ))) } ID & {% for accession, reference in snps %} ((( reference|escape_tex ))){% if not loop.last %}&{% endif %} {% endfor %} \\ \toprule {% for group in grouped_samples %} {% for id, snps in group %} ((( id|escape_tex ))) & {% for snp, type in snps %} {% if type == 'ref' %} {% elif type == 'het' %} \cellcolor{gray!32} {% elif type == 'h**o' %} \cellcolor{gray!128} \color{white} {% endif %} ((( snp ))) {% if not loop.last %}&{% endif %} {% endfor %} \\ {% endfor %} {% if not loop.last %}\midrule{% endif %} {% endfor %} \bottomrule \caption{Reference mismatches. Cells in light gray refer to heterozygous variants, cells in dark grey refer to homozygous variants.} \end{longtable} } \newpage { \sf \begin{longtable}{r{% for id, snps in samples %}r{% endfor %}} \toprule & {% for id, snps in samples %} \rotatebox{90}{\textbf{((( id|escape_tex )))}} {% if not loop.last %}&{% endif %} {% endfor %}\\ \toprule {% for id, snps in samples %} \textbf{((( id|escape_tex )))} & {% set i = loop.index0 %} {% for id, snps in samples %} {% set j = loop.index0 %} {% if i == j %} \multicolumn{1}{c}{--} {% else %} {% if mismatches[i][j] == 0 %} \cellcolor{green!64} {% else %} \cellcolor{gray!((( (mismatches[i][j] / snps|length * 50 )|int )))} {% endif %} ((( mismatches[i][j]|int ))){% endif %} {% if not loop.last %}&{% endif %} {%endfor %} \\ {%endfor %} \bottomrule \caption{Sample/sample mismatches (1 per strand).} \end{longtable} } \end{document} """) return template
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)
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
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 = {
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
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())