/*
Template fields:
Required:
templatePath
subject
to (if user isn't specified)
Optional:
from (use config default if missing)
templateVars (overridden by vars)
489726
function renderMessage(template, user, vars) {
    var appurl = app.getExternalUrl();
    var emailVars = _.defaults(vars || {}, template.templateVars || {}, config.templateVars || {}, {
      'appurl': appurl,
      'settings': app.config.settings
    });
    // XXX should use route resolution fns
    if (user && user.local.signupToken) {
      emailVars.signupLink = appurl + "/verification/" + user.local.signupToken;
    }
    if (user && user.local.resetToken) {
      emailVars.resetLink = appurl + "/forgot/" + user.local.resetToken;
    }

    var msgSubject = swig.render(template.subject, {locals:emailVars});

    var message = {
        from: template.from || config.from,
        to: template.to || user.local.email,
        subject: msgSubject,
    };
    if (template.replyTo) {
      message.replyTo = template.replyTo;
    }

    if (template.templatePath && template.templateName) {
      throw new Error("mail template configuration error: templatePath and templateName cannot both be set");
    }

    if (template.templatePath) {
      message.html = swig.renderFile(template.templatePath, emailVars);
      return message;
    } else {
      message.vars = emailVars;
      message.templateName = template.templateName;
      message.merge_language = template.merge_language || "mailchimp";
      return message;
    }
  }
1005507
function loadTemplate(templatePath, identifier) {
  return plugin.myrmex.fire('beforeTemplateLoad', templatePath, identifier)
  .spread((templatePath, name) => {
    const templateDoc = _.cloneDeep(require(path.join(templatePath)));

    // Lasy loading because the plugin has to be registered in a Myrmex instance before requiring the document
    const Template = require('./template');
    const template = new Template(templateDoc, identifier);

    // This event allows to inject code to alter the template configuration
    return plugin.myrmex.fire('afterTemplateLoad', template);
  })
  .spread(template => {
    return Promise.resolve(template);
  });
}
606178
String createTemplateServerRequest(String servletPath,String templateName) {
        String pathInfo = servletPath.substring(servletPath.indexOf("/",TEMPLATE_LOAD_PROTOCOL.length()));
        if (templateName != null) {            
            pathInfo = pathInfo + templateName;
        }
        return pathInfo;
    }
1222624
function (done) {
      var root = node_path.join(__dirname, 'templates', template);

      fs.exists(root, function(exists){
        if(exists){
          template_root = root;
        }else{
          template_root = node_path.join(DIR_CUSTOM_TEMPLATES, template)
        }
        done(null);
      });
    }
1210710
private void loadTemplates( Element parent )
    {
        // Load templates
        List templates = DomUtils.getChildElementsByName( parent, URL_TEMPLATE );
        for ( int i = 0; i < templates.size(); i++ )
        {
            Element template = ( Element ) templates.get( i );
            String name = getElementText( template, NAME );
            if ( name == null )
            {
                _log.error( "Malformed URL template descriptor in " + _configFilePath
                            + ". The url-template name is missing." );
                continue;
            }

            String value = getElementText( template, VALUE );
            if ( value == null )
            {
                _log.error( "Malformed URL template descriptor in " + _configFilePath
                            + ". The url-template value is missing for template " + name );
                continue;
            }

            if ( _log.isDebugEnabled() )
            {
                _log.debug( "[URLTemplate] " + name + " = " + value );
            }

            URLTemplate urlTemplate = new URLTemplate( value, name );
            if ( urlTemplate.verify( _knownTokens, _requiredTokens ) )
            {
                _urlTemplates.addTemplate( name, urlTemplate );
            }
        }
    }
147377
private static void initURLTemplates( ServletContext servletContext )
    {
        TemplatedURLFormatter formatter = TemplatedURLFormatter.getTemplatedURLFormatter( servletContext );
        if ( formatter == null )
        {
            // get the default template formatter class name from the config file
            formatter = getTemplatedURLFormatter();

            assert formatter != null : "Found a non-null URL formatter";

            // set the TemplatedURLFormatter attribute on the context.
            TemplatedURLFormatter.initServletContext( servletContext, formatter );
        }

        URLTemplatesFactory templatesFactory = URLTemplatesFactory.getURLTemplatesFactory( servletContext );
        if ( templatesFactory == null )
        {
            // URLTemplatesFactory has not been initialized,
            // get a URLTemplatesFactory object from the containerAdapter.
            templatesFactory = PageFlowUtils.createURLTemplatesFactory( servletContext );

            // get the known/req tokens from the default formatter for the factory to use to verify templates
            templatesFactory.setKnownTokens( formatter.getKnownTokens() );
            templatesFactory.setRequiredTokens( formatter.getRequiredTokens() );
            templatesFactory.load( servletContext );

            // set the URLTemplatesFactory attribute on the context.
            URLTemplatesFactory.initServletContext( servletContext, templatesFactory );
        }
    }
524878
function (settings) {
  validatePresenceOfOptions(settings, ['urlTemplate', 'userName']);

  if (settings.templateName) {
    this.endpoints = {
      get: [WindshaftConfig.MAPS_API_BASE_URL, 'named', settings.templateName, 'jsonp'].join('/'),
      post: [WindshaftConfig.MAPS_API_BASE_URL, 'named', settings.templateName].join('/')
    };
  } else {
    this.endpoints = {
      get: WindshaftConfig.MAPS_API_BASE_URL,
      post: WindshaftConfig.MAPS_API_BASE_URL
    };
  }

  this.url = settings.urlTemplate.replace('{user}', settings.userName);
  this._requestTracker = new RequestTracker(MAP_INSTANTIATION_LIMIT);
}
21995
public UriTemplate with(TemplateVariable variable) {

		Assert.notNull(variable, "Template variable must not be null!");

		return with(new TemplateVariables(variable));
	}
882541
function readTemplate(template, syntax, ext, optional) {
			var filename = template
				? path.resolve(template.replace(path.extname(template), ext))
				: path.join(__dirname, 'templates/' + syntax + ext)
			;
			if (fs.existsSync(filename)) {
				return {
					filename: filename,
					template: fs.readFileSync(filename, 'utf8')
				};
			}
			else if (!optional) {
				return grunt.fail.fatal('Cannot find template at path: ' + filename);
			}
		}
500781
public void parseStandalone(
            final IEngineConfiguration configuration,
            final String ownerTemplate,
            final String template,
            final Set<String> templateSelectors,
            final ITemplateResource resource,
            final TemplateMode templateMode,
            final boolean useDecoupledLogic,
            final ITemplateHandler handler) {

        Validate.notNull(configuration, "Engine Configuration cannot be null");
        // ownerTemplate CAN be null if this is a first-level template
        Validate.notNull(template, "Template cannot be null");
        Validate.notNull(resource, "Template Resource cannot be null");
        Validate.isTrue(templateSelectors == null || templateSelectors.isEmpty(),
                        "Template selectors cannot be specified for a template using RAW template mode: template " +
                        "insertion operations must be always performed on whole template files, not fragments");
        Validate.notNull(templateMode, "Template Mode cannot be null");
        Validate.isTrue(templateMode == TemplateMode.RAW, "Template Mode has to be RAW");
        Validate.isTrue(!useDecoupledLogic, "Cannot use decoupled logic in template mode " + templateMode);
        Validate.notNull(handler, "Template Handler cannot be null");

        parse(configuration, ownerTemplate, template, templateSelectors, resource, 0, 0, templateMode, handler);

    }
925326
function () {
    if (config.filters && config.filters.html && config.filters.html.vars) {
        templateVars = _.clone(config.filters.html.vars);
    } else {
        templateVars = {};
    }
}
311727
function getTemplatesList(customPath = null) {
  const predefined = getDirectories(DEFAULT_PATH_TEMPLATES).reduce(createListOfDirectories, {})
  try {
    const custom = customPath ? getDirectories(customPath).reduce(createListOfDirectories, {}) : []

    return { ...predefined, ...custom }
  } catch (error) {
    Logger.warn('The custom templates path that you supply is unreachable')
    Logger.warn('falling back to defaults templates')
    return predefined
  }
}
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;
}
94956
def _load_templates(self, config):
        
        # definition of the template directory
        self.template_dir = self._get_param(
            'resources',
            'templates.dir',
            config
            )
        cherrypy.log.error(
            msg="loading templates from dir '%(dir)s'" %
                {'dir': self.template_dir},
            severity=logging.DEBUG
        )
        # preload templates
        self.temp_lookup = lookup.TemplateLookup(
            directories=self.template_dir, input_encoding='utf-8',
            default_filters=['unicode', 'h']
            )
        # load each template
        self.temp = {}
        for t in ('index.tmpl', 'error.tmpl', 'login.tmpl', '404.tmpl',
                  'searchadmin.tmpl', 'searchuser.tmpl', 'adduser.tmpl',
                  'roles.tmpl', 'groups.tmpl', 'form.tmpl', 'selfmodify.tmpl',
                  'modify.tmpl', 'service_unavailable.tmpl'
                  ):
            self.temp[t] = self.temp_lookup.get_template(t)
251418
def template(path, source, type = :template)
      if source
        template = Template.new(source, @context, source_path: path)
      else
        template_path = case type
                        when :partial
                          find_partial(path)
                        when :layout
                          find_layout(path)
                        else
                          path
                        end

        if template_path && File.exist?(template_path)
          template = Template.open(template_path, @context)
        else
          template_not_found!(type, path)
        end
      end

      prevent_recursion!(template)

      template
    end
1326653
private void initBaseTemplatePath(ServletContext servletContext) {
		if (engine.getSourceFactory() instanceof ClassPathSourceFactory) {
			// do nothing
		} else {
			if (StrKit.isBlank(engine.getBaseTemplatePath())) {
				String path = servletContext.getRealPath("/");
				engine.setBaseTemplatePath(path);
			}
		}
	}
838976
public function renderTemplate($templatePath = null, $data = [])
    {
        $templateData = $this->readTemplate($templatePath);
        if($data === null) {
            throw new Exception("template(): expects parameter 2 to be array, null given");
        }
        foreach($data as $key => $val) {
            if(is_array($val)) {
                $findStart = strpos($templateData, '{{'.$key.':}}');
                if($findStart !== false) {
                    $findEnd = strpos($templateData, '{{:'.$key.'}}');
                    if($findEnd !== false) {
                        $len = 5 + strlen($key);
                        $substr = substr($templateData, $findStart, ($findEnd - $findStart));
                        $substr = substr($substr, $len);
                        $loopstr = []; #fixed-for: Uncaught Error: [] operator not supported for strings $loopstr[]
                        foreach($val as $k => $v) {
                            $temp = $substr;
                            if(is_array($v)) {
                                //$temp = strtr($temp, $v); {{}} not replaced
                                foreach($v as $ks => $vs) {
                                    $temp = str_replace('{{'.$ks.'}}', $vs, $temp);
                                }
                            }
                            else {
                                $temp = str_replace('{{'.$key.'}}', $v, $temp);
                            }
                            $loopstr[] = $temp;
                        }
                        $loopstr = implode("\n", $loopstr);
                        $templateData = str_replace('{{'.$key.':}}'.$substr.'{{:'.$key.'}}', $loopstr, $templateData);
                    }
                    else {
                        throw new Exception('Error in template : loop has not closed properely');
                        exit;
                    }
                }
            }
            else {
                $templateData = str_replace('{{'.$key.'}}', $val, $templateData);
            }
        }
        return $templateData;
    }