Parsing 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
1039405
def parse_from_template(template_name):
    
    thisdir = os.path.split(__file__)[0]
    filename = os.path.join(
        thisdir, '..', 'templates', '%s.xml' % template_name
    )
    with open(filename, 'rb') as f:
        xml = f.read()
    return parse_xml(xml)
1064377
private void parse()
   {
      template = text;
      if (StringUtils.isEmptyTrimmed(template))
         return;
      int index = 0;
      while (template.indexOf("${") != -1)
      {
         int from = template.lastIndexOf("${");
         int to = template.indexOf("}", from + 2);
         if (to == -1)
         {
            template = text;
            complex = false;
            entities.clear();
            return;
         }

         int dv = template.indexOf(":", from + 2);
         if (dv != -1 && dv > to)
         {
            dv = -1;
         }
         String systemProperty = null;
         String defaultValue = null;
         String s = template.substring(from + 2, to);
         if ("/".equals(s))
         {
            systemProperty = File.separator;
         }
         else if (":".equals(s))
         {
            systemProperty = File.pathSeparator;
            dv = -1;
         }
         else
         {
            systemProperty = SecurityActions.getSystemProperty(s);
         }

         if (dv != -1)
         {
            s = template.substring(from + 2, dv);
            systemProperty = SecurityActions.getSystemProperty(s);
            defaultValue = template.substring(dv + 1, to);
         }
         String prefix = "";
         String postfix = "";
         String key = StringUtils.createKey(index++);
         updateComplex(defaultValue);
         entities.put(key, new Expression(s, defaultValue, systemProperty));

         if (from != 0)
         {
            prefix = template.substring(0, from);
         }
         if (to + 1 < template.length())
         {
            postfix = template.substring(to + 1);
         }
         template = prefix + key + postfix;
      }
      updateComplex(template);
   }
1140477
function template(str, params){
  return str.replace(/%(\w*)%/g, function(m, key){
    return params[key];
  });
}
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
375753
protected void parseTemplateString() throws MalformedUriTemplateException
    {
        final String templateString = getTemplate();
        final UriTemplateParser scanner = new UriTemplateParser();
        this.components = scanner.scan(templateString);
        initExpressions();
    }
1130357
protected function _parseExtend() {
        foreach (Template::$_extends as $extend) {
            $this->_content = $extend['class']::$extend['method']($this->_content);
        }

        foreach (Config::instance()->config['user']['template'] as $extend) {
            $this->_content = $extend['class']::$extend['method']($this->_content);
        }
    }
1001577
function readTemplate(path) {
  var template = fs.readFileSync(__dirname + '/templates/' + path, 'utf8');
  for (var index in data) {
    template = template.split('__' + index + '__').join(data[index]);
  }
  return template;
}
3149
function getTemplate(template, options) {
  stack.clear();
  parser.reset();

  let opts = typeof options === 'undefined' ? {} : options;
  opts.strict = typeof opts.strict === 'boolean' ? opts.strict : true;
  opts.preserveWhitespace = typeof opts.preserveWhitespace === 'boolean' ? opts.preserveWhitespace : false;
  opts.validateHtml = opts.validateHtml != null ? opts.validateHtml : 'strict';
  opts.logger = opts.logger != null ? opts.logger : {};

  let lambdas = {};
  if (_.isArray(opts.lambdas)) {
    for (let i = 0; i < opts.lambdas.length; i++) {
      lambdas[opts.lambdas[i]] = true;
    }
  }
  opts.lambdas = lambdas;
  opts.processingHTML = typeof opts.processingHTML === 'boolean' ? opts.processingHTML : true;

  compilerLogger.setStrictMode(opts.strict);
  compilerLogger.setOverrides(opts.logger);
  stack.setHtmlValidation(opts.validateHtml);

  let templateStr = template.toString();

  processTemplate(templateStr, opts);

  let output = {};

  if (stack.stack.length > 0) {
    compilerErrors.notAllTagsWereClosedProperly(stack.stack);
  }

  parser.end();
  output.templateObj = stack.getOutput();
  const Template = require('../template');
  output.template = new Template(output.templateObj);
  output.source = template;
  output.tokens = {};
  _.each(stack.tokens, function(values, type) {
    output.tokens[type] = _.keys(values);
  });
  return output;
}
918574
def parse_template(template_path, **kwargs):
    
    template = get_template(template_path)
    context = Context(kwargs)
    data = template.render(context).strip()
    subject, content = re.split(r'\r?\n', data, 1)
    return (subject.strip(), content.strip())
199536
protected function parseTemplate($template)
	{
		$this->references = [
			'anywhere' => [],
			'asUrl'    => [],
			'inText'   => []
		];

		preg_match_all($this->referencesRegexp, $template, $matches);
		foreach ($matches[0] as $match)
		{
			$key = trim($match, '\\${}');
			$this->references['anywhere'][$key] = $key;
		}

		$dom   = TemplateLoader::load($template);
		$xpath = new DOMXPath($dom);
		foreach ($xpath->query('//text()') as $node)
		{
			preg_match_all($this->referencesRegexp, $node->textContent, $matches);
			foreach ($matches[0] as $match)
			{
				$key = trim($match, '\\${}');
				$this->references['inText'][$key] = $key;
			}
		}

		foreach (NodeLocator::getURLNodes($dom) as $node)
		{
			// We only bother with literal attributes that start with a capture
			if ($node instanceof DOMAttr
			 && preg_match('(^(?:[$\\\\]\\d+|\\$\\{\\d+\\}))', trim($node->value), $m))
			{
				$key = trim($m[0], '\\${}');
				$this->references['asUrl'][$key] = $key;
			}
		}

		$this->removeUnknownReferences();
	}
1299082
def ParsedSections(file_val):
    
    try:
        template_dict = {}
        cur_section = ''
        for val in file_val.split('\n'):
            val = val.strip()
            if val != '':
                section_match = re.match(r'\[.+\]', val)
                if section_match:
                    cur_section = section_match.group()[1:-1]
                    template_dict[cur_section] = {}
                else:
                    option, value = val.split('=', 1)
                    option = option.strip()
                    value = value.strip()
                    if option.startswith('#'):
                        template_dict[cur_section][val] = ''
                    else:
                        template_dict[cur_section][option] = value
    except Exception:  # pragma: no cover
        template_dict = {}
    return template_dict
809539
def parse_mailcap_nametemplate(tmplate='%s'):
    """"""
    nt_list = tmplate.split('%s')
    template_prefix = ''
    template_suffix = ''
    if len(nt_list) == 2:
        template_suffix = nt_list[1]
        template_prefix = nt_list[0]
    else:
        template_suffix = tmplate
    return (template_prefix, template_suffix)
1319382
def match_template(tree, template, args=None):
    
    tokens = get_tokens(template.split())
    cur_args = {}
    if match_tokens(tree, tokens, cur_args):
        if args is not None:
            for k, v in cur_args.items():
                args[k] = v
        logger.debug('MATCHED: {0}'.format(template))
        return True
    else:
        return False
465221
def parse_tag(template, l_del, r_del):
    """"""
    global _CURRENT_LINE
    global _LAST_TAG_LINE

    tag_types = {
        '!': 'comment',
        '#': 'section',
        '^': 'inverted section',
        '/': 'end',
        '>': 'partial',
        '=': 'set delimiter?',
        '{': 'no escape?',
        '&': 'no escape'
    }

    # Get the tag
    try:
        tag, template = template.split(r_del, 1)
    except ValueError:
        raise ChevronError('unclosed tag '
                           'at line {0}'.format(_CURRENT_LINE))

    # Find the type meaning of the first character
    tag_type = tag_types.get(tag[0], 'variable')

    # If the type is not a variable
    if tag_type != 'variable':
        # Then that first character is not needed
        tag = tag[1:]

    # If we might be a set delimiter tag
    if tag_type == 'set delimiter?':
        # Double check to make sure we are
        if tag.endswith('='):
            tag_type = 'set delimiter'
            # Remove the equal sign
            tag = tag[:-1]

        # Otherwise we should complain
        else:
            raise ChevronError('unclosed set delimiter tag\n'
                               'at line {0}'.format(_CURRENT_LINE))

    # If we might be a no html escape tag
    elif tag_type == 'no escape?':
        # And we have a third curly brace
        # (And are using curly braces as delimiters)
        if l_del == '{{' and r_del == '}}' and template.startswith('}'):
            # Then we are a no html escape tag
            template = template[1:]
            tag_type = 'no escape'

    # Strip the whitespace off the key and return
    return ((tag_type, tag.strip()), template)
329612
private void parseTemplateVariables() throws MiniTemplator.TemplateSyntaxException {
        int p = 0;
        while (true) {
            p = templateText.indexOf("${", p);
            if (p == -1) {
                break;
            }
            int p0 = p;
            p = templateText.indexOf("}", p);
            if (p == -1) {
                throw new MiniTemplator.TemplateSyntaxException(
                        "Invalid variable reference in template at offset " + p0 + ".");
            }
            p++;
            String varName = templateText.substring(p0 + 2, p - 1).trim();
            if (varName.length() == 0) {
                throw new MiniTemplator.TemplateSyntaxException(
                        "Empty variable name in template at offset " + p0 + ".");
            }
            registerVariableReference(varName, p0, p);
        }
    }
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']