How to use the mako.template function in Mako

To help you get started, we’ve selected a few Mako examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github laanwj / mesa / src / intel / isl / gen_format_layout.py View on Github external
# SOFTWARE.

"""Generates isl_format_layout.c."""

from __future__ import absolute_import, division, print_function
import argparse
import csv
import re
import textwrap

from mako import template

# Load the template, ensure that __future__.division is imported, and set the
# bytes encoding to be utf-8. This last bit is important to getting simple
# consistent behavior for python 3 when we get there.
TEMPLATE = template.Template(future_imports=['division'],
                             output_encoding='utf-8',
                             text="""\
/* This file is autogenerated by gen_format_layout.py. DO NOT EDIT! */

/*
 * Copyright 2015 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
github AppEnlight / appenlight-client-python / appenlight_client / tests.py View on Github external
def test_render_call_number(self):
        try:
            import mako
        except ImportError:
            return
        template = mako.template.Template('''
        <%
        import time
        time.sleep(0.01)
        %>
        xxxxx ${1+2} yyyyyy
        ''')
        template.render()
        template.render()
        template.render()
        stats, result = get_local_storage(local_timing).get_thread_stats()
        self.assertEqual(stats['tmpl_calls'], 3)
github stoq / stoq / external / mako / exceptions.py View on Github external
def _init(self):
        """format a traceback from sys.exc_info() into 7-item tuples, containing
        the regular four traceback tuple items, plus the original template
        filename, the line number adjusted relative to the template source, and
        code line from that line number of the template."""
        import mako.template
        mods = {}
        (type, value, trcback) = sys.exc_info()
        rawrecords = traceback.extract_tb(trcback)
        new_trcback = []
        for filename, lineno, function, line in rawrecords:
            try:
                (line_map, template_lines) = mods[filename]
            except KeyError:
                try:
                    info = mako.template._get_module_info(filename)
                    module_source = info.code
                    template_source = info.source
                    template_filename = info.template_filename or filename
                except KeyError:
                    new_trcback.append((filename, lineno, function, line, None, None, None, None))
                    continue

                template_ln = module_ln = 1
                line_map = {}
                for line in module_source.split("\n"):
                    match = re.match(r'\s*# SOURCE LINE (\d+)', line)
                    if match:
                        template_ln = int(match.group(1))
                    else:
                        template_ln += 1
                    module_ln += 1
github WhiteMagic / JoystickGremlin / mako / exceptions.py View on Github external
fp = open(filename, 'rb')
                            encoding = util.parse_encoding(fp)
                            fp.close()
                        except IOError:
                            encoding = None
                        if encoding:
                            line = line.decode(encoding)
                        else:
                            line = line.decode('ascii', 'replace')
                    new_trcback.append((filename, lineno, function, line,
                                        None, None, None, None))
                    continue

                template_ln = 1

                source_map = mako.template.ModuleInfo.\
                    get_module_source_metadata(
                        module_source, full_line_map=True)
                line_map = source_map['full_line_map']

                template_lines = [line_ for line_ in
                                  template_source.split("\n")]
                mods[filename] = (line_map, template_lines)

            template_ln = line_map[lineno - 1]

            if template_ln <= len(template_lines):
                template_line = template_lines[template_ln - 1]
            else:
                template_line = None
            new_trcback.append((filename, lineno, function,
                                line, template_filename, template_ln,
github multiversecoder / pug4py / pug4py / pug.py View on Github external
"""
        Render the file using mako

        Parameters
        ----------
            filename: str
                the name of the file to render using mako
            kwargs

        Returns
        -------
            str
                the content of the rendered file
        """
        with open(f"{self.template_dir}/{filename}") as tpl:
            tpl = mako.template.Template(
                tpl.read(), strict_undefined=True).render(**kwargs)
        return tpl
github NetBSD / xsrc / external / mit / MesaLib / dist / src / compiler / nir / nir_algebraic.py View on Github external
# Try all possible pairings of source items and add the
               # corresponding parent items. This is Comp_a from the paper.
               parent = set(self.items[op, item_srcs] for item_srcs in
                  itertools.product(*srcs) if (op, item_srcs) in self.items)

               # We could always start matching something else with a
               # wildcard. This is Cl from the paper.
               parent.add(self.wildcard)

               table[src_indices] = self.states.add(frozenset(parent))
            worklist_indices[op] = len(rep)
         new_opcodes.clear()
         process_new_states()

_algebraic_pass_template = mako.template.Template("""
#include "nir.h"
#include "nir_builder.h"
#include "nir_search.h"
#include "nir_search_helpers.h"

#ifndef NIR_OPT_ALGEBRAIC_STRUCT_DEFS
#define NIR_OPT_ALGEBRAIC_STRUCT_DEFS

struct transform {
   const nir_search_expression *search;
   const nir_search_value *replace;
   unsigned condition_offset;
};

struct per_op_table {
   const uint16_t *filter;
github tensorflow / moonlight / moonlight / training / clustering / kmeans_labeler_request_handler.py View on Github external
def do_GET(self):
    template_path = resource_loader.get_path_to_datafile(
        'kmeans_labeler_template.html')
    template = mako_template.Template(open(template_path).read())
    page = create_page(self.clusters, template)
    self.send_response(http_client.OK)
    self.send_header('Content-Type', 'text/html; charset=utf-8')
    self.end_headers()
    self.wfile.write(page)
github stevenbell / zynqbuilder / drivers / drivergen.py View on Github external
paramFile = "../hwconfig.yml"
templateFiles = {"driver.c.mako":"driver.c", "dma_bufferset.h.mako":"dma_bufferset.h"}

params = yaml.load(open(paramFile))

params['toolName'] = "drivergen.py"
params['date'] = time.asctime()

# The stream names are specified in the file, but we need an ordered list
# to be sure things like function calls work.
params['streamNames'] = params['instreams'].keys() + params['outstreams'].keys()

for f in templateFiles:
  src = open(f).read()
  try:
    template = mako.template.Template(src)
    output = open(templateFiles[f], 'w')
    output.write(template.render(**params))
    output.close()
  except:
    print(mako.exceptions.text_error_template().render())
github zzzeek / mako / mako / exceptions.py View on Github external
def text_error_template(lookup=None):
    """Provides a template that renders a stack trace in a similar format to
    the Python interpreter, substituting source template filenames, line
    numbers and code for that of the originating source template, as
    applicable.

    """
    import mako.template

    return mako.template.Template(
        r"""
<%page args="error=None, traceback=None"/>
<%!
    from mako.exceptions import RichTraceback
%>\
<%
    tback = RichTraceback(error=error, traceback=traceback)
%>\
Traceback (most recent call last):
% for (filename, lineno, function, line) in tback.traceback:
  File "${filename}", line ${lineno}, in ${function or '?'}
    ${line | trim}
% endfor
${tback.errorname}: ${tback.message}
"""
    )
github virtool / virtool / virtool / http / auth.py View on Github external
def get_client_file_error_template() -> mako.template.Template:
    """
    A convenience function for getting a :class:`~mako.template.Template` for an error page returned when the client
    files cannot be found.

    :return: an error page template

    """
    return mako.template.Template(filename=os.path.join(sys.path[0], "templates", "client_path_error.html"))