How to use the mako.template.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 sqlalchemy / mako / test / test_filters.py View on Github external
def test_url_escaping(self):
        t = Template(
            """
            http://example.com/?bar=${bar | u}&v=1
        """
        )

        eq_(
            flatten_result(t.render(bar=u"酒吧bar")),
            "http://example.com/?bar=%E9%85%92%E5%90%A7bar&v=1",
        )
github sqlalchemy / mako / test / __init__.py View on Github external
def _file_template(self, filename, **kw):
        filepath = self._file_path(filename)
        return Template(
            uri=filename, filename=filepath, module_directory=module_base, **kw
        )
github ElementsProject / lightning / devtools / changelog.py View on Github external
def group(entries):
    groups = {s: [] for s in sections}
    for e in entries:
        groups[e.section].append(e)
    return groups


def commit_date(commitsha):
    """Get the date of the specified commit.
    """
    line = git("show -s --format=%ci")
    dt = datetime.strptime(line.strip(), '%Y-%m-%d %H:%M:%S %z')
    return dt


template = Template("""<%def name="group(entries)">
% for e in entries:
 - ${e.content} ([${e.pullreq}](https://github.com/ElementsProject/lightning/pull/${e.pullreq}))
% endfor



${h2} [${version}] - ${date.strftime("%Y-%m-%d")}: "CODENAME"

This release named by @USERNAME.

${h3} Added
${group(groups['added']) | trim}
${h3} Changed
${group(groups['changed']) | trim}
github mdevaev / emonoda / emonoda / plugins / confetti / __init__.py View on Github external
def templated(name: str, built_in: bool=True, **kwargs: Any) -> str:
    if built_in:
        data = pkgutil.get_data(__name__, os.path.join("templates", name))
        assert data, (data, name, __name__)
        text = data.decode()
    else:
        with open(name) as template_file:
            text = template_file.read()
    template = textwrap.dedent(text).strip()
    return mako.template.Template(template).render(**kwargs).strip()
github inducer / boxtree / boxtree / distributed / local_tree.py View on Github external
fetch_local_paticles_arguments.render(
            mask_t=dtype_to_ctype(global_tree.particle_id_dtype),
            coord_t=dtype_to_ctype(global_tree.coord_dtype),
            ndims=global_tree.dimensions,
            particles_have_extent=global_tree.targets_have_extent
        ),
        fetch_local_particles_prg.render(
            particle_id_t=dtype_to_ctype(global_tree.particle_id_dtype),
            ndims=global_tree.dimensions,
            particles_have_extent=global_tree.targets_have_extent
        )
    )

    generate_box_particle_starts = cl.elementwise.ElementwiseKernel(
        context,
        Template("""
            __global ${particle_id_t} *old_starts,
            __global ${particle_id_t} *particle_scan,
            __global ${particle_id_t} *new_starts
        """, strict_undefined=True).render(
            particle_id_t=dtype_to_ctype(global_tree.particle_id_dtype)
        ),
        "new_starts[i] = particle_scan[old_starts[i]]",
        name="generate_box_particle_starts"
    )

    generate_box_particle_counts_nonchild = cl.elementwise.ElementwiseKernel(
        context,
        Template("""
            __global char *res_boxes,
            __global ${particle_id_t} *old_counts_nonchild,
            __global ${particle_id_t} *new_counts_nonchild
github rembo10 / headphones / mako / lookup.py View on Github external
def put_string(self, uri, text):
        """Place a new :class:`.Template` object into this
        :class:`.TemplateLookup`, based on the given string of
        ``text``.

        """
        self._collection[uri] = Template(
                                    text,
                                    lookup=self,
                                    uri=uri,
                                    **self.template_args)
github Luxoft / Twister / server / CeWebUi.py View on Github external
    @cherrypy.expose
    def set_user_status(self, user, status):
        """ Update user status """
        logFull('CeWebUi:set_user_status user `{}`.'.format(user))
        output = Template(filename=TWISTER_PATH + '/server/template/rest_error.htm')
        try:
            status = int(status)
        except:
            return output.render(title='Error!', body='<b>Status value `{0}` is invalid!</b>'.format(status))
        if status not in EXEC_STATUS.values():
            return output.render(title='Error!', body='<b>Status value `{0}`' \
                ' is not in the list of valid statuses: {1}!</b>'\
                .format(status, EXEC_STATUS.values()))
        self.project.set_exec_status_all(user, status, 'User status changed from REST interface.')
        raise cherrypy.HTTPRedirect('http://{host}/web/users/{user}#tab_home'.\
        format(host=cherrypy.request.headers['Host'], user=user))
github galaxyproject / galaxy / lib / galaxy / tools / __init__.py View on Github external
except:
                log.exception( "error in help for tool %s" % self.name )

            # Handle deprecated multi-page help text in XML case.
            if hasattr(tool_source, "root"):
                help_elem = tool_source.root.find("help")
                help_header = help_text
                help_pages = help_elem.findall( "page" )
                # Multiple help page case
                if help_pages:
                    for help_page in help_pages:
                        self.__help_by_page.append( help_page.text )
                        help_footer = help_footer + help_page.tail
                # Each page has to rendered all-together because of backreferences allowed by rst
                try:
                    self.__help_by_page = [ Template( rst_to_html( help_header + x + help_footer ),
                                                      input_encoding='utf-8', output_encoding='utf-8',
                                                      default_filters=[ 'decode.utf8' ],
                                                      encoding_errors='replace' )
                                            for x in self.__help_by_page ]
                except:
                    log.exception( "error in multi-page help for tool %s" % self.name )
        # Pad out help pages to match npages ... could this be done better?
        while len( self.__help_by_page ) &lt; self.npages:
            self.__help_by_page.append( self.__help )
github StatisKit / AutoWIG / src / py / autowig / boost_python_generator.py View on Github external
language = 'c++'

    SCOPE = Template(text=r"""\
% for scope in scopes:

    std::string name_${scope.hash} = boost::python::extract&lt; std::string &gt;(boost::python::scope().attr("__name__") + ".${node_rename(scope, scope=True)}");
    boost::python::object module_${scope.hash}(boost::python::handle&lt;  &gt;(boost::python::borrowed(PyImport_AddModule(name_${scope.hash}.c_str()))));
    boost::python::scope().attr("${node_rename(scope, scope=True)}") = module_${scope.hash};
    boost::python::scope scope_${scope.hash} = module_${scope.hash};\
% endfor""")

    ENUMERATOR = Template(text="""\
    boost::python::scope().attr("${node_rename(enumerator)}") = (int)(${enumerator.globalname});\
""")

    ENUMERATION = Template(text=r"""\
    boost::python::enum_&lt; ${enumeration.globalname.replace("enum ", "")} &gt; enum_${enumeration.hash}("${node_rename(enumeration)}");
    % if enumeration.is_scoped:
        % for enumerator in enumeration.enumerators:
            % if enumerator.boost_python_export:
    enum_${enumeration.hash}.value("${node_rename(enumerator)}", ${enumerator.globalname});
            % endif
        % endfor
    % else:
        % for enumerator in enumeration.enumerators:
            % if enumerator.boost_python_export:
    enum_${enumeration.hash}.value("${node_rename(enumerator)}", ${enumerator.globalname[::-1].replace((enumeration.localname + '::')[::-1], '', 1)[::-1]});
            % endif
        % endfor
    % endif""")

    VARIABLE = Template(text="""\
github Luxoft / Twister / server / CeReports.py View on Github external
    @cherrypy.expose
    def index(self, usr=''):
        logFull('CeReports:index')

        if not usr:
            users = self.project.listUsers()
            output = Template(filename=TWISTER_PATH + '/server/template/rep_base.htm')
            return output.render(title='Users', usr='#' + '#'.join(users), links=[])

        if not os.path.isdir(userHome(usr) + '/twister/config'):
            return '<br><b>Error! Username `{}` doesn\'t have a Twister config folder!</b>'.format(usr)

        # FORCE re-load all Database XML on INDEX/ HOME links !
        self.load_config(usr, True)
        output = Template(filename=TWISTER_PATH + '/server/template/rep_base.htm')
        return output.render(title='Home', usr=usr, links=self.glob_links[usr])