Python pystache.render() Examples

The following are 19 code examples of pystache.render(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pystache , or try the search function .
Example #1
Source File: injector.py    From base16-builder-python with MIT License 6 votes vote down vote up
def get_colorscheme(self, scheme_file):
        """Return a string object with the colorscheme that is to be
        inserted."""
        scheme = get_yaml_dict(scheme_file)
        scheme_slug = builder.slugify(scheme_file)
        builder.format_scheme(scheme, scheme_slug)

        try:
            temp_base, temp_sub = self.temp.split("##")
        except ValueError:
            temp_base, temp_sub = (self.temp.strip("##"), "default")

        temp_path = rel_to_cwd("templates", temp_base)
        temp_group = builder.TemplateGroup(temp_path)
        try:
            single_temp = temp_group.templates[temp_sub]
        except KeyError:
            raise FileNotFoundError(None, None, self.path + " (sub-template)")

        colorscheme = pystache.render(single_temp["parsed"], scheme)
        return colorscheme 
Example #2
Source File: reader.py    From dcos-deploy with Apache License 2.0 6 votes vote down vote up
def read_file(self, filename, render_variables=False, as_binary=False):
        if filename.startswith("vault:"):
            if filename.startswith("vault::"):
                if not self.global_config or "vault" not in self.global_config or "key" not in self.global_config["vault"]:
                    raise ConfigurationException("vault definition without key but no key is defined in global config: %s" % filename)
                _, filename = filename.split("::", 1)
                key = self.variables_container.render(self.global_config["vault"]["key"])
            else:
                _, key, filename = filename.split(":", 2)
        else:
            key = None
        filepath = self.abspath(filename)
        mode = "r"
        if as_binary:
            mode = "rb"
        with open(filepath, mode) as file_obj:
            data = file_obj.read()
        if key:
            check_if_encrypted_is_older(filepath)
            data = decrypt_data(key, data)
        if render_variables:
            data = self.variables_container.render(data)
        return data 
Example #3
Source File: Pystache.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def render(self, template, dictionary):
        return pystache.render(template, **dictionary) 
Example #4
Source File: docobject.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def markdown_links(self):
        DocObject.use_links = True
        fmt = inspect.cleandoc(self.DETAILED_FMT_MD)
        return pystache.render(fmt, self) 
Example #5
Source File: docobject.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def markdown(self):
        DocObject.use_links = False
        fmt = inspect.cleandoc(self.DETAILED_FMT_MD)
        return pystache.render(fmt, self) 
Example #6
Source File: docobject.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def detailed(self):
        fmt = inspect.cleandoc(self.DETAILED_FMT_PLAIN)
        return pystache.render(fmt, self) 
Example #7
Source File: docobject.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def compact(self):
        fmt = inspect.cleandoc(self.COMPACT_FMT)
        return pystache.render(fmt, self) 
Example #8
Source File: sparql_transformer.py    From kgx with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_networkx_graph(self, rdfgraph: rdflib.Graph = None, predicates: Set[URIRef] = None, **kwargs) -> None:
        """
        Fetch triples from the SPARQL endpoint and load them as edges.

        Parameters
        ----------
        rdfgraph: rdflib.Graph
            A rdflib Graph (unused)
        predicates: set
            A set containing predicates in rdflib.URIRef form
        kwargs: dict
            Any additional arguments.

        """
        for predicate in predicates:
            predicate = '<{}>'.format(predicate)
            q = render(self.edge_query, {'predicate': predicate})
            results = self.query(q)
            for r in results:
                s = r['subject']['value']
                p = r['predicate']['value']
                o = r['object']['value']
                if r['object']['type'] == 'literal':
                    self.add_node_attribute(s, key=p, value=o)
                else:
                    self.add_edge(s, o, p) 
Example #9
Source File: generator.py    From mbed-cli with Apache License 2.0 5 votes vote down vote up
def generateCompleters(commands):
    txt = []

    renderer = pystache.Renderer(escape=lambda u: u)

    with open("templates/command.tmplt") as fp:
        tmplt = fp.read()

    for commandKey in commands:
        txt.append(renderer.render(tmplt, commands[commandKey]))

        # if need to add hacks add them here

    return txt 
Example #10
Source File: generator.py    From mbed-cli with Apache License 2.0 5 votes vote down vote up
def generateMain(commands):
    txt = []

    with open("templates/mbed.tmplt") as fp:
        tmplt = fp.read()

    txt.append(pystache.render(tmplt, commands))

    return txt 
Example #11
Source File: attribute_generation.py    From SATOSA with Apache License 2.0 5 votes vote down vote up
def _synthesize(self, attributes, requester, provider):
        syn_attributes = dict()
        context = dict()
        
        for attr_name,values in attributes.items():
           context[attr_name] = MustachAttrValue(attr_name, values)

        recipes = get_dict_defaults(self.synthetic_attributes, requester, provider)
        for attr_name, fmt in recipes.items():
           syn_attributes[attr_name] = [v.strip().strip(';') for v in re.split("[;\n]+", pystache.render(fmt, context))]
        return syn_attributes 
Example #12
Source File: reader.py    From dcos-deploy with Apache License 2.0 5 votes vote down vote up
def _expand_loop(key, values):
    loop = values["loop"]
    del values["loop"]
    extra_vars = values.get("extra_vars", dict())
    loop_vars = loop.keys()
    if "{{" in key:
        name_template = key
    else:
        name_template = "%s-%s" % (key, '-'.join(["{{%s}}" % var for var in loop_vars]))
    for combination in itertools.product(*[loop[var] for var in loop_vars]):
        variables = {**extra_vars, **dict([(var, combination[idx]) for idx, var in enumerate(loop_vars)])}
        name = pystache.render(name_template, variables)
        entity_config = copy.deepcopy(values)
        entity_config["extra_vars"] = variables
        yield name, entity_config 
Example #13
Source File: reader.py    From dcos-deploy with Apache License 2.0 5 votes vote down vote up
def render(self, text):
        if text is None:
            return None
        return self.variables_container.render(text) 
Example #14
Source File: variables.py    From dcos-deploy with Apache License 2.0 5 votes vote down vote up
def render_value(self, value, extra_vars=dict()):
        if extra_vars:
            variables = {**self.variables, **extra_vars}
        else:
            variables = self.variables
        return pystache.render(value, variables) 
Example #15
Source File: variables.py    From dcos-deploy with Apache License 2.0 5 votes vote down vote up
def _read_variable_value_from_file(self, base_path, fileconfig):
        if isinstance(fileconfig, dict):
            filename = fileconfig["path"]
            render = fileconfig.get("render", False)
        else:
            filename = fileconfig
            render = False
        if filename.startswith("vault:"):
            _, key, filename = filename.split(":", 2)
            if not key:
                if not self._vault_key:
                    raise ConfigurationException("vault definition without key but no key is defined in global config: %s" % filename)
                key = self._vault_key
        else:
            key = None
        filename = self.render_value(filename)
        absolute_path = os.path.abspath(os.path.join(base_path, filename))
        if key:
            check_if_encrypted_is_older(absolute_path)
        with open(absolute_path) as var_file:
            value = var_file.read()
        if key:
            key = self.render_value(key)
            value = decrypt_data(key, value)
        if render:
            value = pystache.render(value, self.variables)
        return value 
Example #16
Source File: variables.py    From dcos-deploy with Apache License 2.0 5 votes vote down vote up
def render(self, text):
        variables = {**self.variables, **self.extra_vars}
        result_text = pystache.render(text, variables)
        if result_text.count("{{"):
            raise ConfigurationException("Unresolved variable")
        return result_text 
Example #17
Source File: model.py    From genanki with MIT License 4 votes vote down vote up
def _req(self):
    """
    List of required fields for each template. Format is [tmpl_idx, "all"|"any", [req_field_1, req_field_2, ...]].

    Partial reimplementation of req computing logic from Anki. We use pystache instead of Anki's custom mustache
    implementation.

    The goal is to figure out which fields are "required", i.e. if they are missing then the front side of the note
    doesn't contain any meaningful content.
    """
    sentinel = 'SeNtInEl'
    field_names = [field['name'] for field in self.fields]

    req = []
    for template_ord, template in enumerate(self.templates):
      field_values = {field: sentinel for field in field_names}
      required_fields = []
      for field_ord, field in enumerate(field_names):
        fvcopy = copy(field_values)
        fvcopy[field] = ''

        rendered = pystache.render(template['qfmt'], fvcopy)

        if sentinel not in rendered:
          # when this field is missing, there is no meaningful content (no field values) in the question, so this field
          # is required
          required_fields.append(field_ord)

      if required_fields:
        req.append([template_ord, 'all', required_fields])
        continue

      # there are no required fields, so an "all" is not appropriate, switch to checking for "any"
      field_values = {field: '' for field in field_names}
      for field_ord, field in enumerate(field_names):
        fvcopy = copy(field_values)
        fvcopy[field] = sentinel

        rendered = pystache.render(template['qfmt'], fvcopy)

        if sentinel in rendered:
          # when this field is present, there is meaningful content in the question
          required_fields.append(field_ord)

      if not required_fields:
        raise Exception(
          'Could not compute required fields for this template; please check the formatting of "qfmt": {}'.format(
            template))

      req.append([template_ord, 'any', required_fields])

    return req 
Example #18
Source File: sparql_transformer.py    From kgx with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def load_networkx_graph(self, rdfgraph: rdflib.Graph = None, predicates: Set[URIRef] = None, **kwargs: Dict) -> None:
        """
        Fetch all triples using the specified predicates and add them to networkx.MultiDiGraph.

        Parameters
        ----------
        rdfgraph: rdflib.Graph
            A rdflib Graph (unused)
        predicates: set
            A set containing predicates in rdflib.URIRef form
        kwargs: dict
            Any additional arguments.
            Ex: specifying 'limit' argument will limit the number of triples fetched.

        """
        for predicate in predicates:
            sparql = SPARQLWrapper(self.url)
            association = '<{}>'.format(predicate)
            query = render(self.count_query, {'association': association})
            logging.debug(query)
            sparql.setQuery(query)
            sparql.setReturnFormat(JSON)
            results = sparql.query().convert()
            count = int(results['results']['bindings'][0]['triples']['value'])
            logging.info("Expected triples for query: {}".format(count))
            step = 1000
            start = 0
            for i in range(step, count + step, step):
                end = i
                query = render(self.edge_query, {'association': association, 'offset': start, 'limit':step})
                sparql.setQuery(query)
                logging.debug("Fetching triples with predicate {}".format(predicate))
                results = sparql.query().convert()
                node_list = set()
                for r in results['results']['bindings']:
                    node_list.add("<{}>".format(r['subject']['value']))
                    node_list.add("<{}>".format(r['object']['value']))
                start = end
                self.load_nodes(node_list)
                for r in results['results']['bindings']:
                    s = r['subject']['value']
                    p = r['predicate']['value']
                    o = r['object']['value']
                    self.add_edge(s, o, p)
                    # TODO: preserve edge properties

                if 'limit' in kwargs and i > kwargs['limit']:
                    break

        self.categorize() 
Example #19
Source File: builder.py    From base16-builder-python with MIT License 4 votes vote down vote up
def build_single(scheme_file, job_options):
    """Build colorscheme from $scheme_file using $job_options. Return True if
    completed without warnings. Otherwise false."""
    scheme = get_yaml_dict(scheme_file)
    scheme_slug = slugify(scheme_file)
    format_scheme(scheme, scheme_slug)
    scheme_name = scheme["scheme-name"]
    warn = False  # set this for feedback to the caller

    if job_options.verbose:
        print('Building colorschemes for scheme "{}"...'.format(scheme_name))

    for temp_group in job_options.templates:

        for _, sub in temp_group.templates.items():
            output_dir = os.path.join(
                job_options.base_output_dir, temp_group.name, sub["output"]
            )
            try:
                os.makedirs(output_dir)
            except FileExistsError:
                pass

            if sub["extension"] is not None:
                filename = "base16-{}{}".format(scheme_slug, sub["extension"])
            else:
                filename = "base16-{}".format(scheme_slug)

            build_path = os.path.join(output_dir, filename)

            # include a warning for files being overwritten to comply with
            # base16 0.9.1
            if os.path.isfile(build_path):
                verb_msg("File {} exists and will be overwritten.".format(build_path))
                warn = True

            async with aiofiles.open(build_path, "w") as file_:
                file_content = pystache.render(sub["parsed"], scheme)
                await file_.write(file_content)

            if job_options.verbose:
                print('Built colorschemes for scheme "{}".'.format(scheme_name))

    return not (warn)