/*
Compile template, replace placeholder with their values

Parameters:
- template (string): string with placeholders, i.e. 'Hello {{name}}'
- context (object): key/value pairs, i.e. {name: 'World'}
169911
function compile(template, context) {
        for (var name in context) {
            template = template.replace('{{' + name + '}}', context[name])
        }
        return template
    }
1166444
def make_placeholders(seq, start=1):
    
    if len(seq) == 0:
        raise ValueError('Sequence must have at least one element.')
    param_style = Context.current().param_style
    placeholders = None
    if isinstance(seq, dict):
        if param_style in ('named', 'pyformat'):
            template = ':%s' if param_style == 'named' else '%%(%s)s'
            placeholders = (template % key
                            for key in six.iterkeys(seq))
    elif isinstance(seq, (list, tuple)):
        if param_style == 'numeric':
            placeholders = (':%d' % i
                            for i in xrange(start, start + len(seq)))
        elif param_style in ('qmark', 'format', 'pyformat'):
            placeholders = itertools.repeat(
                '?' if param_style == 'qmark' else '%s',
                len(seq))
    if placeholders is None:
        raise NotSupported(
            "Param style '%s' does not support sequence type '%s'" % (
                param_style, seq.__class__.__name__))
    return ', '.join(placeholders)
1359440
def _handle_template_param_value(self):
        """"""
        self._emit_all(self._pop())
        self._context ^= contexts.TEMPLATE_PARAM_KEY
        self._context |= contexts.TEMPLATE_PARAM_VALUE
        self._emit(tokens.TemplateParamEquals())
906611
def render_to_string(template_name, context=None, request=None, using=None):
    
    if isinstance(template_name, (list, tuple)):
        template = select_template(template_name, using=using)
    else:
        template = get_template(template_name, using=using)
    return template.render(context, request)
861882
def render_template_file(template, context=None):
    
    assert isinstance(context, Mapping)
    template = get_template(template)
    return template.render(context)
968852
function compile(template) {
    el = $compile(template)(pageScope);
    root = $rootElement.append(el)[0];
    body = $document[0].body;
    body.appendChild(root);

    pageScope.$apply();

    return el;
  }
561030
function flattenContext(template, ctx) {
    var arr, result = {};

    while ((arr = re.exec(template)) !== null) {
        if (arr[1]) {
            var value = reach(ctx, arr[1]);
            result[arr[1]] = value && value.toString();
        }
    }

    return result;
}
1045572
function builtTemplateFromString(str, filename, options) {

  try {
    var config = {};

    // config at the beginning of the file
    str.replace(settings.config, function(m, conf) {
      config = yaml.safeLoad(conf);
    });

    // strip comments
    if (settings.stripComment) {
      str = str.replace(settings.comment, function(m, code, assign, value) {
        return '';
      });
    }

    // strip whitespace
    if (settings.stripWhitespace) {
      settings.dot.strip = settings.stripWhitespace;
    }

    // layout sections
    var sections = {};

    if (!config.layout) {
      sections.body = str;
    }
    else {
      str.replace(settings.dot.define, function(m, code, assign, value) {
        sections[code] = value;
      });
    }

    var templateSettings = _.pick(options, ['settings']);
    options.getTemplate && (templateSettings.getTemplate = options.getTemplate);
    return new Template({
      express: templateSettings,
      config: config,
      sections: sections,
      dirname: path.dirname(filename),
      filename: filename
    });
  }
  catch (err) {
    throw new Error(
      'Failed to build template' +
      ' (' + filename + ')' +
      ' - ' + err.toString()
    );
  }
}
745278
function setTemplateContext(contextArray) {

      var newTemplateContext = {};
      contextArray.forEach(function(item) {
        var cleanString = item.slice(options.contextBinderMark.length, -options.contextBinderMark.length),
          separatedPairs = cleanString.split(':');

        newTemplateContext[separatedPairs[0]] = separatedPairs[1];
      });
      options.templateContext = newTemplateContext;
    }
289625
def create_template_context(self, element, **kwargs):
        """"""
        context = dict(element=element, **kwargs)
        if self.global_context:
            context.update(**self.global_context)
        return context
565361
function template(tmpl, context) {
			return tmpl.replace(/\{([^\}]+)\}/g, function(m, key) {
				return context[key];
			});
		}
467669
def parse_placeholder(parser, token):
    """"""
    bits = token.split_contents()
    count = len(bits)
    error_string = '%r tag requires at least one argument' % bits[0]
    if count <= 1:
        raise TemplateSyntaxError(error_string)
    name = bits[1]
    remaining = bits[2:]
    params = {}
    simple_options = ['parsed', 'inherited', 'untranslated']
    param_options = ['as', 'on', 'with']
    all_options = simple_options + param_options
    while remaining:
        bit = remaining[0]
        if bit not in all_options:
            raise TemplateSyntaxError(
                "%r is not an correct option for a placeholder" % bit)
        if bit in param_options:
            if len(remaining) < 2:
                raise TemplateSyntaxError(
                "Placeholder option '%s' need a parameter" % bit)
            if bit == 'as':
                params['as_varname'] = remaining[1]
            if bit == 'with':
                params['widget'] = remaining[1]
            if bit == 'on':
                params['page'] = remaining[1]
            remaining = remaining[2:]
        elif bit == 'parsed':
            params['parsed'] = True
            remaining = remaining[1:]
        elif bit == 'inherited':
            params['inherited'] = True
            remaining = remaining[1:]
        elif bit == 'untranslated':
            params['untranslated'] = True
            remaining = remaining[1:]
    return name, params
1371846
function compileTemplates() {
  const mainHtml = fs.readFileSync(path.resolve(docsDir, 'src/template.html'), {
    encoding: 'utf8',
  });
  const mainTemplate = Handlebars.compile(mainHtml);

  function createPage(fileName, tab, content) {
    const html = mainTemplate({
      tabs: [{
        title: 'Get started',
        url: 'get-started.html',
        selected: tab === 'get-started',
      }, {
        title: 'Components',
        url: 'components.html',
        selected: tab === 'components',
      }],
      content,
      luiVersion: LUI_VERSION,
    });
    fileUtil.writeFile(path.resolve(docsDir, 'dist', fileName), html);
  }

  function createIndexPage() {
    const content = fs.readFileSync(path.resolve(docsDir, 'src/pages/index.html'), {
      encoding: 'utf8',
    });
    const template = Handlebars.compile(content);
    const html = template();
    return createPage('index.html', 'index', html);
  }

  function createGetStartedPage() {
    const content = fs.readFileSync(path.resolve(docsDir, 'src/pages/get-started.html'), {
      encoding: 'utf8',
    });
    const template = Handlebars.compile(content);
    const html = template({
      luiVersion: LUI_VERSION,
    });
    return createPage('get-started.html', 'get-started', html);
  }

  function createComponentPage(templateName, template, tab, content) {
    return createPage(templateName, tab, template({
      content,
      sections: sections.map(section => ({
        name: section.name,
        pages: section.pages.map(page => ({
          name: page.name,
          template: page.template,
          selected: page.template === templateName,
        })),
      })),
    }));
  }

  function createComponentPages() {
    const componentHtml = fs.readFileSync(path.resolve(docsDir, 'src/component-template.html'), {
      encoding: 'utf8',
    });
    const componentTemplate = Handlebars.compile(componentHtml);

    sections.forEach((section) => {
      section.pages.forEach((page) => {
        const file = `src/pages/${page.template}`;
        const fileContent = fs.readFileSync(path.resolve(docsDir, file), {
          encoding: 'utf8',
        });

        const template = Handlebars.compile(fileContent);
        const html = template();

        createComponentPage(page.template, componentTemplate, 'components', html);
      });
    });

    const file = 'src/pages/components.html';
    const fileContent = fs.readFileSync(path.resolve(docsDir, file), {
      encoding: 'utf8',
    });
    createComponentPage('components.html', componentTemplate, 'components', fileContent);
  }

  createIndexPage();
  createGetStartedPage();
  createComponentPages();
}
1130935
def template(template_name, *, app_key=APP_KEY, encoding='utf-8', status=200):
    

    def wrapper(func):
        @functools.wraps(func)
        async def wrapped(*args, **kwargs):
            if asyncio.iscoroutinefunction(func):
                coro = func
            else:
                coro = asyncio.coroutine(func)
            context = await coro(*args, **kwargs)
            if isinstance(context, web.StreamResponse):
                return context

            if 'request' in kwargs:
                request = kwargs['request']
            elif not args:
                request = None
                warnings.warn("Request not detected")
            elif isinstance(args[0], AbstractView):
                request = args[0].request
            else:
                request = args[-1]

            response = render_template(template_name, request, context,
                                       app_key=app_key, encoding=encoding)
            response.set_status(status)
            return response
        return wrapped
    return wrapper
1150592
def render_to_string(self, template_name, context=None):
        """"""
        # create an empty context if no context was specified
        context = context or {}
        tmpl = self.get_template(template_name)
        # render the template into a unicode string (None means unicode)
        return tmpl. \
            generate(**context). \
            render(self.output_type, encoding=None)
491529
def template(*args, **kwargs):
    '''
    
    '''
    tpl = args[0] if args else None
    template_adapter = kwargs.pop('template_adapter', SimpleTemplate)
    if tpl not in TEMPLATES or DEBUG:
        settings = kwargs.pop('template_settings', {})
        lookup = kwargs.pop('template_lookup', TEMPLATE_PATH)
        if isinstance(tpl, template_adapter):
            TEMPLATES[tpl] = tpl
            if settings: TEMPLATES[tpl].prepare(**settings)
        elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl:
            TEMPLATES[tpl] = template_adapter(source=tpl, lookup=lookup, **settings)
        else:
            TEMPLATES[tpl] = template_adapter(name=tpl, lookup=lookup, **settings)
    if not TEMPLATES[tpl]:
        abort(500, 'Template (%s) not found' % tpl)
    for dictarg in args[1:]: kwargs.update(dictarg)
    return TEMPLATES[tpl].render(kwargs)
1103283
def prepare(self, context):
        
        self.params = {}

        # no params, not even a newline
        if not self.nodelist:
            return

        # just static text, no vars, assume one TextNode
        if not self.nodelist.contains_nontext:
            text = self.nodelist[0].s.strip()

        # vars in params, we have to render
        else:
            context.push()
            context['object'] = self.obj
            text = self.nodelist.render(context)
            context.pop()

        if text:
            self.params = self.resolve_params(text)

        # override the default template from the parameters
        if 'template_name' in self.params:
            self.template_name = self.params['template_name']