Execute the information stored in a string from an sls template

    CLI Example:

    .. code-block:: bash

        salt '*' state.template_str '<Template String>'
515629
def template_str(tem, queue=False, **kwargs):
    '''
    
    '''
    conflict = _check_queue(queue, kwargs)
    if conflict is not None:
        return conflict

    opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)

    try:
        st_ = salt.state.State(opts,
                               proxy=__proxy__,
                               initial_pillar=_get_initial_pillar(opts))
    except NameError:
        st_ = salt.state.State(opts, initial_pillar=_get_initial_pillar(opts))
    ret = st_.call_template_str(tem)
    _set_retcode(ret)
    return ret
568075
def __render(template, state, index=0):
    
    # Find a Match
    match = state.tag_re.search(template, index)
    if not match:
        return template[index:]

    info = get_match_info(template, match, state)
    _pre = template[index : info['tag_start']] # template before the tag
    _tag = template[info['tag_start'] : info['tag_end']] # tag
    _continue = info['tag_end'] # the index at which to continue

    # Comment
    if info['tag_type'] == '!':
        # Comments are removed from output
        repl = ""

    # Delimiter change
    elif info['tag_type'] == '=':
        # Delimiters are changed; the tag is rendered as ""
        delimiters = re.split(r'\s*', info['tag_key'])
        new_tags = state.tags(_copy=True)
        new_tags['otag'], new_tags['ctag'] = map(re.escape, delimiters)
        state.push_tags(new_tags)
        repl = ""

    # Plain tag
    elif info['tag_type'] == '':
        repl = __render_tag(info, state)

    # Raw tag (should not be escaped)
    elif info['tag_type'] == '&':
        state.escape.push(False)
        repl = __render_tag(info, state)
        state.escape.pop()

    # Partial
    elif info['tag_type'] == '>':
        partial_name = info['tag_key']
        partial_template = None
        new_dir = None
        lead_wsp = re.compile(r'^(.)', re.M)
        repl = ''
        try:
            # Cached
            partial_template = state.partials()[partial_name]
        except (KeyError, IndexError):
            try:
                # Load the partial template from a file (if it exists)
                new_dir, filename = split(partial_name)
                if new_dir:
                    state.partials_dir.push(new_dir)

                partial_template = load_template(filename, state.abs_partials_dir, state.extension,
                                                 state.encoding, state.encoding_error)
            except (IOError):
                pass

        if partial_template:
            # Preserve indentation
            if info['standalone']:
                partial_template = lead_wsp.sub(info['lead_wsp']+r'\1', partial_template)

            # Update state
            state.partials.push(state.partials()) # XXX wtf is this shit?
            state.push_tags(state.default_tags)

            # Render the partial
            repl = __render(partial_template, state)

            # Restore state
            state.partials.pop()
            state.pop_tags()
            if new_dir:
                state.partials_dir.pop()

    # Section

    # TODO(peter): add a stop= index to __render so that template_to_inner does
    # not need to be constructed with [:] indexing, which is extremely
    # expensive.
    elif info['tag_type'] in ('#', '^'):
        otag_info = info
        ctag_info = section_end_info(template, info['tag_key'], state, _continue)

        # Don't want to parse beyond the end of the inner section, but
        # must include information on prior contents so that whitespace
        # is preserved correctly and inner tags are not marked as standalone.
        inner_start = otag_info['tag_end']
        inner_end = ctag_info['tag_start']
        _continue = ctag_info['tag_end']

        template_with_inner = template[:inner_end]

        new_contexts, ctm = get_tag_context(otag_info['tag_key'], state)
        truthy = otag_info['tag_type'] == '#'

        #if ctm is not None:
        if ctm:
            # If there's a match and it's callable, feed it the inner template
            if callable(ctm):
                template_to_inner = template[:inner_start]
                inner = template[inner_start:inner_end]
                template_with_inner = template_to_inner + make_unicode(ctm(inner))

            # Make the context list an iterable from the ctm
            if not hasattr(ctm, '__iter__') or isinstance(ctm, dict):
                ctx_list = [ctm]
            else:
                ctx_list = ctm
        # If there's no match, there are no new contexts
        else:
            ctx_list = [False]

        # If there are new contexts and the section is truthy, or if
        # there are no new contexts and the section is falsy, render
        # the contents
        repl_stack = []
        for ctx in ctx_list:
            if (truthy and ctx) or (not truthy and not ctx):
                state.context.push(ctx)
                repl_stack.append(
                    __render(template_with_inner, state, inner_start))

            else:
                break

        repl = ''.join(repl_stack)
        for i in xrange(new_contexts): state.context.pop()
    else:
        raise Exception("found unpaired end of section tag!")

    return u''.join((
        _pre, make_unicode(repl), __render(template, state, _continue)))
987625
public String process(String templateName, String templateSource, Map<String, Object> params) {
        try {
            Template template = new Template(templateName, templateSource, configuration);
            Writer writer = new StringWriter();
            template.process(params, writer);
            return writer.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
1036571
def pattern_from_template(templates, name):
    

    if name not in templates:
        echo("No template named \"%s\"" % name)
        sys.exit(1)

    return templates[name]
362547
def build_from_template(file)
      context = @options[:context] || {}

      template = IO.read(file)
      eruby = Erubis::Eruby.new(template)
      string = eruby.evaluate(context)
      build_from_string(string, File.dirname(file))
    end
38916
def from_string(self, source, globals=None, template_class=None):
        
        globals = self.make_globals(globals)
        cls = template_class or self.template_class
        return cls.from_code(self, self.compile(source), globals, None)
129204
def render_pstate(self, sls, saltenv, mods, defaults=None):
        '''
        
        '''
        if defaults is None:
            defaults = {}
        err = ''
        errors = []
        state_data = self.client.get_state(sls, saltenv)
        fn_ = state_data.get('dest', False)
        if not fn_:
            if sls in self.ignored_pillars.get(saltenv, []):
                log.debug('Skipping ignored and missing SLS \'%s\' in '
                          'environment \'%s\'', sls, saltenv)
                return None, mods, errors
            elif self.opts['pillar_roots'].get(saltenv):
                msg = ('Specified SLS \'{0}\' in environment \'{1}\' is not'
                       ' available on the salt master').format(sls, saltenv)
                log.error(msg)
                errors.append(msg)
            else:
                msg = ('Specified SLS \'{0}\' in environment \'{1}\' was not '
                       'found. '.format(sls, saltenv))
                if self.opts.get('__git_pillar', False) is True:
                    msg += (
                        'This is likely caused by a git_pillar top file '
                        'containing an environment other than the one for the '
                        'branch in which it resides. Each git_pillar '
                        'branch/tag must have its own top file.'
                    )
                else:
                    msg += (
                        'This could be because SLS \'{0}\' is in an '
                        'environment other than \'{1}\', but \'{1}\' is '
                        'included in that environment\'s Pillar top file. It '
                        'could also be due to environment \'{1}\' not being '
                        'defined in \'pillar_roots\'.'.format(sls, saltenv)
                    )
                log.debug(msg)
                # return state, mods, errors
                return None, mods, errors
        state = None
        try:
            state = compile_template(fn_,
                                     self.rend,
                                     self.opts['renderer'],
                                     self.opts['renderer_blacklist'],
                                     self.opts['renderer_whitelist'],
                                     saltenv,
                                     sls,
                                     _pillar_rend=True,
                                     **defaults)
        except Exception as exc:
            msg = 'Rendering SLS \'{0}\' failed, render error:\n{1}'.format(
                sls, exc
            )
            log.critical(msg, exc_info=True)
            if self.opts.get('pillar_safe_render_error', True):
                errors.append(
                    'Rendering SLS \'{0}\' failed. Please see master log for '
                    'details.'.format(sls)
                )
            else:
                errors.append(msg)
        mods.add(sls)
        nstate = None
        if state:
            if not isinstance(state, dict):
                msg = 'SLS \'{0}\' does not render to a dictionary'.format(sls)
                log.error(msg)
                errors.append(msg)
            else:
                if 'include' in state:
                    if not isinstance(state['include'], list):
                        msg = ('Include Declaration in SLS \'{0}\' is not '
                               'formed as a list'.format(sls))
                        log.error(msg)
                        errors.append(msg)
                    else:
                        # render included state(s)
                        include_states = []

                        matched_pstates = []
                        for sub_sls in state.pop('include'):
                            if isinstance(sub_sls, dict):
                                sub_sls, v = next(six.iteritems(sub_sls))
                                defaults = v.get('defaults', {})
                                key = v.get('key', None)
                            else:
                                key = None

                            try:
                                if sub_sls.startswith('.'):
                                    if state_data.get('source', '').endswith('/init.sls'):
                                        include_parts = sls.split('.')
                                    else:
                                        include_parts = sls.split('.')[:-1]
                                    sub_sls = '.'.join(include_parts+[sub_sls[1:]])
                                matches = fnmatch.filter(
                                    self.avail[saltenv],
                                    sub_sls,
                                )
                                matched_pstates.extend(matches)
                            except KeyError:
                                errors.extend(
                                    ['No matching pillar environment for environment '
                                     '\'{0}\' found'.format(saltenv)]
                                )

                        for sub_sls in matched_pstates:
                            if sub_sls not in mods:
                                nstate, mods, err = self.render_pstate(
                                        sub_sls,
                                        saltenv,
                                        mods,
                                        defaults
                                        )
                                if nstate:
                                    if key:
                                        # If key is x:y, convert it to {x: {y: nstate}}
                                        for key_fragment in reversed(key.split(":")):
                                            nstate = {
                                                key_fragment: nstate
                                            }
                                    if not self.opts.get('pillar_includes_override_sls', False):
                                        include_states.append(nstate)
                                    else:
                                        state = merge(
                                            state,
                                            nstate,
                                            self.merge_strategy,
                                            self.opts.get('renderer', 'yaml'),
                                            self.opts.get('pillar_merge_lists', False))
                                if err:
                                    errors += err

                        if not self.opts.get('pillar_includes_override_sls', False):
                            # merge included state(s) with the current state
                            # merged last to ensure that its values are
                            # authoritative.
                            include_states.append(state)
                            state = None
                            for s in include_states:
                                if state is None:
                                    state = s
                                else:
                                    state = merge(
                                        state,
                                        s,
                                        self.merge_strategy,
                                        self.opts.get('renderer', 'yaml'),
                                        self.opts.get('pillar_merge_lists', False))
        return state, mods, errors
440659
def command_template(self):
        
        com_out = self.appname
        arg_string = ""
        flag_string = ""
        # Loop over the key, value pairs in self.args

        for key, val in self.args.items():
            # Check if the value is set in self._options
            # If so, get the value from there
            if val is None:
                opt_val = self._options[key][0]
            else:
                opt_val = val
            opt_type = self._options[key][2]
            if key == 'args':
                # 'args' is special, pull it out and move it to the back
                arg_string += ' {%s}' % key
            elif opt_type is bool:
                if opt_val:
                    flag_string += ' --%s' % (key)
            elif opt_type is list:
                if is_null(opt_val):
                    continue
                elif isinstance(opt_val, str):
                    com_out += ' --%s %s' % (key, opt_val)
                elif isinstance(opt_val, list):
                    for arg_val in opt_val:
                        com_out += ' --%s %s' % (key, arg_val)
            else:
                com_out += ' --%s {%s}' % (key, key)
        com_out += flag_string
        com_out += arg_string
        return com_out
1052770
async function getTemplate({template, preset}) {
	if (typeof template === 'string') {
		return template;
	}

	if (typeof preset === 'string') {
		try {
			return (
				await read(
					resolve(
						__dirname,
						'templates',
						[preset.toLowerCase(), 'html'].join('.'),
					)
				)
			).toString();
		} catch (error) {
			throw new Error(`Preset ${preset} not found`);
		}
	}

	return DEFAULT_TEMPLATE;
}
174984
def _parse_template(tmpl_str):
    '''
    
    '''
    tmpl_str = tmpl_str.strip()
    if tmpl_str.startswith('{'):
        tpl = salt.utils.json.loads(tmpl_str)
    else:
        try:
            tpl = salt.utils.yaml.safe_load(tmpl_str)
        except salt.utils.yaml.YAMLError as exc:
            raise ValueError(six.text_type(exc))
        else:
            if tpl is None:
                tpl = {}
    if not ('HeatTemplateFormatVersion' in tpl
            or 'heat_template_version' in tpl
            or 'AWSTemplateFormatVersion' in tpl):
        raise ValueError(('Template format version not found.'))
    return tpl
303756
def get_template(
            self,
            url,
            dest,
            template='jinja',
            makedirs=False,
            saltenv='base',
            cachedir=None,
            **kwargs):
        '''
        
        '''
        if 'env' in kwargs:
            # "env" is not supported; Use "saltenv".
            kwargs.pop('env')

        kwargs['saltenv'] = saltenv
        url_data = urlparse(url)
        sfn = self.cache_file(url, saltenv, cachedir=cachedir)
        if not sfn or not os.path.exists(sfn):
            return ''
        if template in salt.utils.templates.TEMPLATE_REGISTRY:
            data = salt.utils.templates.TEMPLATE_REGISTRY[template](
                sfn,
                **kwargs
            )
        else:
            log.error(
                'Attempted to render template with unavailable engine %s',
                template
            )
            return ''
        if not data['result']:
            # Failed to render the template
            log.error('Failed to render template with error: %s', data['data'])
            return ''
        if not dest:
            # No destination passed, set the dest as an extrn_files cache
            dest = self._extrn_path(url, saltenv, cachedir=cachedir)
            # If Salt generated the dest name, create any required dirs
            makedirs = True

        destdir = os.path.dirname(dest)
        if not os.path.isdir(destdir):
            if makedirs:
                os.makedirs(destdir)
            else:
                salt.utils.files.safe_rm(data['data'])
                return ''
        shutil.move(data['data'], dest)
        return dest
768437
def _exec_template(callable_, context, args=None, kwargs=None):
    
    template = context._with_template
    if template is not None and \
            (template.format_exceptions or template.error_handler):
        try:
            callable_(context, *args, **kwargs)
        except Exception:
            _render_error(template, context, compat.exception_as())
        except:
            e = sys.exc_info()[0]
            _render_error(template, context, e)
    else:
        callable_(context, *args, **kwargs)
234978
def run_info(template):
    
    template.project_name = 'TowelStuff' # fake project name, always the same
    name = template_name_from_class_name(template.__class__.__name__)
    term = TerminalView()
    term.print_info("Content of template {} with an example project " \
          "named 'TowelStuff':".format(term.text_in_color(name, TERM_GREEN)))

    dir_name = None
    for file_info in sorted(template.files(), key=lambda dir: dir[0]):
        directory = file_name = template_name = ''
        if file_info[0]:
            directory = file_info[0]
        if file_info[1]:
            file_name = file_info[1]
        if file_info[2]:
            template_name = '\t\t - ' + file_info[2]
        if (directory != dir_name):
            term.print_info('\n\t' + term.text_in_color(directory + '/', TERM_PINK))
            dir_name = directory

        term.print_info('\t\t' + term.text_in_color(file_name, TERM_YELLOW) + template_name)

    # print substitutions
    try:
        subs = template.substitutes().keys()
        if len(subs) > 0:
            subs.sort()
            term.print_info("\nSubstitutions of this template are: ")
            max_len = 0
            for key in subs:
                if max_len < len(key):
                    max_len = len(key)
            for key in subs:
                term.print_info(u"\t{0:{1}} -> {2}".
                format(key, max_len, template.substitutes()[key]))
    except AttributeError:
        pass
254338
def _get_template_from_string(self, ostmpl):
        '''
        
        '''
        self._get_tmpl_env()
        template = self._tmpl_env.from_string(ostmpl.config_template)
        log('Loaded a template from a string for {}'.format(
            ostmpl.config_file),
            level=INFO)
        return template
1138416
def template(cls, address=None, commandtuple=None,
                 userdata=None, cmd2=-1, flags=None, acknak=None):
        """"""
        msgraw = bytearray([0x02, cls._code])
        msgraw.extend(bytes(cls._receivedSize))
        msg = ExtendedSend.from_raw_message(msgraw)

        if commandtuple:
            cmd1 = commandtuple.get('cmd1')
            cmd2out = commandtuple.get('cmd2')
        else:
            cmd1 = None
            cmd2out = None

        if cmd2 is not -1:
            cmd2out = cmd2

        msg._address = Address(address)
        msg._messageFlags = MessageFlags(flags)
        msg._messageFlags.extended = 1
        msg._cmd1 = cmd1
        msg._cmd2 = cmd2out
        msg._userdata = Userdata.template(userdata)
        msg._acknak = acknak
        return msg
1138277
def __execute_str(self, instr):
        
        op0_val = self.read_operand(instr.operands[0])

        self.write_operand(instr.operands[2], op0_val)

        return None
292713
def do_template(self,args):
        """"""
        parser = CommandArgumentParser("template")
        args = vars(parser.parse_args(args))

        print "reading template for stack."
        rawStack = self.wrappedStack['rawStack']
        template = AwsConnectionFactory.getCfClient().get_template(StackName=rawStack.name)
        print template['TemplateBody']