try loading the given template
@param tmplName
@param engine
@param callerClass
@param codeType
@param processTagName
@return the template Class
15783
private TemplateClass tryLoadTemplate(String tmplName, RythmEngine engine, TemplateClass callerClass, ICodeType codeType, boolean processTagName) {
        //logger.info(">>> try load %s on [%s] with processTagName: %s", tmplName, callerClass.getKey(), processTagName);
        if (null == engine) {
            engine = getDefaultEngine();
        }
        if (engine.templateRegistered(tmplName)) {
            return null;
        }
        String rythmSuffix = engine.conf().resourceNameSuffix();
        final List<String> suffixes = new ArrayList<String>(Arrays.asList(RythmEngine.VALID_SUFFIXES));
        if (null == codeType) {
            codeType = TemplateResourceBase.getTypeOfPath(engine, tmplName);
        }
        if (ICodeType.DefImpl.RAW == codeType) {
            // use caller's code type
            codeType = callerClass.codeType;
        }
        final String tagNameOrigin = tmplName;
        boolean hasSuffix = false;
        String suffix = "";
        if (processTagName) {
            boolean withRythmSuffix = S.notEmpty(rythmSuffix);
            for (String s : suffixes) {
                if (tmplName.endsWith(s)) {
                    tmplName = tmplName.substring(0, tmplName.lastIndexOf(s));
                    suffix = s;
                    hasSuffix = true;
                    break;
                }
                if (withRythmSuffix && (tmplName.endsWith(s) || tmplName.endsWith(s + rythmSuffix))) {
                    tmplName = tmplName.substring(0, tmplName.lastIndexOf(s));
                    suffix = s + rythmSuffix;
                    hasSuffix = true;
                    break;
                }
            }
        }
        tmplName = tmplName.replace('.', '/');
        String sfx = codeType.resourceNameSuffix();
        if (S.notEmpty(sfx) && !suffixes.get(0).equals(sfx)) {
            suffixes.remove(sfx);
            suffixes.add(0, sfx);
        }

        final List<String> roots = new ArrayList<String>();
        String root0 = this.getResourceLoaderRoot().replace('\\', '/');
        if (root0.endsWith("/")) {
            root0 = root0.substring(0, root0.length() - 1);
        }

        roots.add(root0);

        // call template using relative path
        String currentPath = callerClass.getKey().toString();
        int pos = currentPath.lastIndexOf("/");
        if (-1 != pos) {
            currentPath = currentPath.substring(0, pos);
            if (currentPath.startsWith(root0)) {
                if (currentPath.length() > root0.length()) {
                    roots.add(0, currentPath);
                }
            } else {
                if (currentPath.startsWith("/")) {
                    currentPath = currentPath.substring(1);
                }
                if (!currentPath.startsWith(root0)) currentPath = root0 + "/" + currentPath;
                roots.add(0, currentPath);
            }
        }
        
        // call tag with import path
        if (null != callerClass.importPaths) {
            for (String s: callerClass.importPaths) {
                if (s.startsWith("java")) {
                    continue;
                }
                roots.add(0, root0 + "/" + s.replace('.', '/'));
            }
        }

        String tmplName0 = tmplName;
        for (String root : roots) {
            String tmplName1 = tmplName0;
            if (root.startsWith("/") && !tmplName1.startsWith("/")) {
                tmplName1 = "/" + tmplName0;
            }
            tmplName = tmplName1.startsWith(root) ? tmplName1 : root + "/" + tmplName0;
            if (hasSuffix) {
                ITemplateResource resource = load(tmplName + suffix);
                if (null == resource || !resource.isValid()) {
                    continue;
                }
                TemplateClass tc = engine.resourceManager().resourceLoaded(resource, false);
                return tc;
            } else {
                for (String suffix0 : suffixes) {
                    String path = tmplName + suffix0;
                    ITemplateResource resource = load(path);
                    if (null == resource || !resource.isValid()) {
                        continue;
                    }
                    TemplateClass tc = engine.resourceManager().resourceLoaded(resource, false);
                    return tc;
                }
            }
        }
        TemplateClass tc = processTagName ? tryLoadTemplate(tagNameOrigin, engine, callerClass, codeType, false) : null;
        if (null == tc) {
            TemplateResourceManager.reportNonResource(tmplName);
        }
        return tc;
    }
346156
private Templates tryCache(String url) throws Exception {
        Templates x = (Templates) m_cache.get(url);
        if (x == null) {
            synchronized (m_cache) {
                if (!m_cache.containsKey(url)) {
                    TransformerFactory factory = TransformerFactory.newInstance();
                    if (factory.getClass().getName().equals("net.sf.saxon.TransformerFactoryImpl")) {
                        factory.setAttribute(FeatureKeys.VERSION_WARNING, Boolean.FALSE);
                    }
                    StreamSource ss = new StreamSource(getInputStream(url));
                    ss.setSystemId(url);
                    x = factory.newTemplates(ss);
                    m_cache.put(url, x);
                }
            }
        }
        return x;
    }
1171683
def load(file,line=None,options={},block=None):
    ''' 
    '''

    template_class = Lean.get_template(file)
    if template_class:
      return template_class(file,line,options,block)
    else:
      raise LookupError('No template engine registered for ' + os.path.basename(file))
686126
public void loadTemplateClass(TemplateClass tc) {
        if (!readEnabled()) {
            return;
        }
        InputStream is = null;
        try {
            File f = getCacheFile(tc);
            if (!f.exists() || !f.canRead()) return;
            is = new BufferedInputStream(new FileInputStream(f));

            // --- check hash
            int offset = 0;
            int read;
            StringBuilder hash = new StringBuilder();
            while ((read = is.read()) != 0) {
                if (read == -1) {
                    logger.error("Failed to read cache file for template class: %s", tc);
                    return;
                }
                hash.append((char) read);
                offset++;
            }

            //check hash only in non precompiled mode
            if (!conf.loadPrecompiled()) {
                String curHash = hash(tc);
                if (!curHash.equals(hash.toString())) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Bytecode too old (%s != %s)", hash, curHash);
                    }
                    return;
                }
            }

            // --- load java source
            read = -1;
            StringBuilder source = new StringBuilder();
            while ((read = is.read()) != 0) {
                source.append((char) read);
                offset++;
            }
            if (source.length() != 0) {
                String s = source.toString();
                String[] sa = s.split("__INCLUDED_TAG_TYPES__");
                tc.javaSource = sa[0];
                s = sa[1];
                sa = s.split("__INCULDED_TEMPLATE_CLASS_NAME_LIST__");
                tc.deserializeIncludeTagTypes(sa[0]);
                s = sa[1];
                sa = s.split("__IMPORT_PATH_LIST__");
                tc.setIncludeTemplateClassNames(sa[0]);
                if (sa.length > 1) {
                    s = sa[1];
                    sa = s.split(";");
                    Set<String> importPaths = new HashSet<String>();
                    for (String path : sa) {
                        if ("java.lang".equals(path)) continue;
                        importPaths.add(path);
                    }
                    tc.replaceImportPath(importPaths);
                }
            } // else it must be an inner class

            // --- load byte code
            byte[] byteCode = new byte[(int) f.length() - (offset + 2)];
            is.read(byteCode);
            tc.loadCachedByteCode(byteCode);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            if(is != null)
                try {
                    is.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
        }
    }
748351
function load(cb) {
    var timer = u.timer();
    generator.getSources(opts.sources, opts, function(err, fragments) {

      if (err) return cb && cb(err);

      generator.fragments = fragments;
      generator.fragment$ = u.indexBy(generator.fragments, '_href');

      var pageFragments = u.filter(fragments, function(fragment) {
        return !fragment._compile;
      });
      compilePages(pageFragments);

      var templateFragments = u.where(fragments, { _compile: 'handlebars' } );
      compileTemplates(templateFragments);

      generator.emit('load');    // hook custom loaders
      generator.emit('loaded');  // then announce loaded

      debug('loaded %sms', timer());
      cb && cb();
    });
  }
1094244
public static final ITemplate getTemplate(String tmpl, Object ... args) {
        return engine().getTemplate(tmpl, args);
    }
677999
private void resolveTypeTemplates() {
        Collections.sort(context.getClassesAlreadyDone(), new Comparator<Java4CppType>() {

            @Override
            public int compare(Java4CppType t1, Java4CppType t2) {
                Class<?> o1 = t1.getRawClass();
                Class<?> o2 = t2.getRawClass();
                if (o1.isArray() && o2.isArray()) {
                    int idx1 = o1.getName().lastIndexOf('[');
                    int idx2 = o2.getName().lastIndexOf('[');
                    if (idx1 == idx2) {
                        return o1.getName().compareTo(o2.getName());
                    }
                    return idx1 < idx2 ? -1 : 1;
                } else if (o1.isArray() && !o2.isArray()) {
                    return 1;
                } else if (!o1.isArray() && o2.isArray()) {
                    return -1;
                }
                return o1.getName().compareTo(o2.getName());
            }
        });
        for (Java4CppType type : context.getClassesAlreadyDone()) {
            context.executeTypeTemplate(type);
        }
    }
859533
static Class<?> loadType(String fullName) throws ClassNotFoundException {
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            return loader != null ? loader.loadClass(fullName) : Class.forName(fullName);
        } catch (ClassNotFoundException ex) {
            return loadPrimitiveType(fullName, ex);
        }
    }
243503
private void loadProtoClassToCache(String key, Class clazz, String methodName) {
        Method pbMethod = null;
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            if (methodName.equals(method.getName())) {
                pbMethod = method;
                break;
            }
        }
        if (pbMethod == null) {
            throw new SofaRpcRuntimeException("Cannot found protobuf method: " + clazz.getName() + "." + methodName);
        }
        Class[] parameterTypes = pbMethod.getParameterTypes();
        if (parameterTypes == null
            || parameterTypes.length != 1
            || isProtoBufMessageObject(parameterTypes[0])) {
            throw new SofaRpcRuntimeException("class based protobuf: " + clazz.getName()
                + ", only support one protobuf parameter!");
        }
        Class reqClass = parameterTypes[0];
        requestClassCache.put(key, reqClass);
        Class resClass = pbMethod.getReturnType();
        if (resClass == void.class || !isProtoBufMessageClass(resClass)) {
            throw new SofaRpcRuntimeException("class based protobuf: " + clazz.getName()
                + ", only support return protobuf message!");
        }
        responseClassCache.put(key, resClass);
    }
58926
void initialize(AbstractCompiler compiler) throws Exception {
    checkState(
        !Strings.isNullOrEmpty(templateJs),
        "The template JS must be loaded before the scanner is used. "
            + "Make sure that the template file is not empty.");
    Node scriptRoot = new JsAst(SourceFile.fromCode(
        "template", templateJs)).getAstRoot(compiler);

    // The before-templates are kept in a LinkedHashMap, to ensure that they are later iterated
    // over in the order in which they appear in the template JS file.
    LinkedHashMap<String, Node> beforeTemplates = new LinkedHashMap<>();
    Map<String, SortedMap<Integer, Node>> afterTemplates = new HashMap<>();
    Set<String> hasChoices = new HashSet<>();
    for (Node templateNode : scriptRoot.children()) {
      if (templateNode.isFunction()) {
        String fnName = templateNode.getFirstChild().getQualifiedName();
        if (fnName.startsWith("before_")) {
          String templateName = fnName.substring("before_".length());
          Preconditions.checkState(
              !beforeTemplates.containsKey(templateName),
              "Found existing template with the same name: %s", beforeTemplates.get(templateName));
          checkState(
              templateNode.getLastChild().hasChildren(),
              "Before templates are not allowed to be empty!");
          beforeTemplates.put(templateName, templateNode);
        } else if (fnName.startsWith("after_option_")) {
          Matcher m = AFTER_CHOICE_PATTERN.matcher(fnName);
          checkState(m.matches(), "Template name %s must match pattern after_option_\\d*_", fnName);
          int optionNumber = Integer.parseInt(m.group(1));
          String templateName = m.group(2);
          if (!afterTemplates.containsKey(templateName)) {
            afterTemplates.put(templateName, new TreeMap<>());
            hasChoices.add(templateName);
          }
          checkState(
              hasChoices.contains(templateName),
              "Template %s can only be mixed with other after_option_ templates");
          checkState(
              !afterTemplates.get(templateName).containsKey(optionNumber),
              "Found duplicate template for %s, assign unique indexes for options",
              fnName);
          afterTemplates.get(templateName).put(optionNumber, templateNode);
        } else if (fnName.startsWith("after_")) {
          String templateName = fnName.substring("after_".length());
          Preconditions.checkState(
              !afterTemplates.containsKey(templateName),
              "Found existing template with the same name: %s", afterTemplates.get(templateName));
          afterTemplates.put(templateName, ImmutableSortedMap.of(0, templateNode));
        } else if (fnName.startsWith("do_not_change_")) {
          String templateName = fnName.substring("do_not_change_".length());
          Preconditions.checkState(
              !beforeTemplates.containsKey(templateName),
              "Found existing template with the same name: %s",
              beforeTemplates.get(templateName));
          Preconditions.checkState(
              !afterTemplates.containsKey(templateName),
              "Found existing template with the same name: %s",
              afterTemplates.get(templateName));
          beforeTemplates.put(templateName, templateNode);
          afterTemplates.put(templateName, ImmutableSortedMap.of(0, templateNode));
        }
      }
    }

    checkState(
        !beforeTemplates.isEmpty(),
        "Did not find any RefasterJs templates! Make sure that there are 2 functions defined "
            + "with the same name, one with a \"before_\" prefix and one with a \"after_\" prefix");

    // TODO(bangert): Get ImmutableLinkedMap into Guava?
    this.templates = new LinkedHashMap<>();
    for (String templateName : beforeTemplates.keySet()) {
      Preconditions.checkState(
          afterTemplates.containsKey(templateName) && !afterTemplates.get(templateName).isEmpty(),
          "Found before template without at least one corresponding after "
              + " template. Make sure there is an after_%s or after_option_1_%s function defined.",
          templateName,
          templateName);
      ImmutableList.Builder<RefasterJsTemplate> builder = ImmutableList.builder();
      for (Node afterTemplateOption : afterTemplates.get(templateName).values()) {
        builder.add(
            new RefasterJsTemplate(
                compiler.getTypeRegistry(),
                typeMatchingStrategy,
                beforeTemplates.get(templateName),
                afterTemplateOption));
      }
      ImmutableList<RefasterJsTemplate> afterOptions = builder.build();
      this.templates.put(afterOptions.get(0).matcher, afterOptions);
    }
  }
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
94938
private void renderTemplate(TemplateNode template, Predicate<String> paramsToTypeCheck) {
    env = Environment.create(template, data, ijData);
    checkStrictParamTypes(template, paramsToTypeCheck);
    visitChildren(template);
    env = null; // unpin for gc
  }
1038077
public String template(String template, Map<String,Object> data)
            throws ScriptException,ScriptLimitException,SyntaxException{
        return template(null,template,data);
    }
341957
def get_template(self, template_name):
        """"""
        try:
            return self.loader.load(template_name, encoding=self.encoding)
        except self.not_found_exception, e:
            # catch the exception raised by Genshi, convert it into a werkzeug
            # exception (for the sake of consistency)
            raise TemplateNotFound(template_name)
543850
public TemplateClass __getTemplateClass(boolean useCaller) {
        TemplateClass tc = __templateClass;
        if (useCaller && null == tc) {
            TemplateBase caller = __caller();
            if (null != caller) return caller.__getTemplateClass(true);
        }
        return tc;
    }
122953
public ApiResponse<Templates> postTemplatesWithHttpInfo() throws ApiException {
        com.squareup.okhttp.Call call = postTemplatesValidateBeforeCall(null, null);
        Type localVarReturnType = new TypeToken<Templates>(){}.getType();
        return apiClient.execute(call, localVarReturnType);
    }
799590
function template(templateSpec, env) {
            /* istanbul ignore next */
            if (!env) {
                throw new Exception("No environment passed to template");
            }
            if (!templateSpec || !templateSpec.main) {
                throw new Exception('Unknown template object: ' + typeof templateSpec);
            }

            // Note: Using env.VM references rather than local var references throughout this section to allow
            // for external users to override these as psuedo-supported APIs.
            env.VM.checkRevision(templateSpec.compiler);

            var invokePartialWrapper = function(partial, indent, name, context, hash, helpers, partials, data, depths) {
                if (hash) {
                    context = Utils.extend({}, context, hash);
                }

                var result = env.VM.invokePartial.call(this, partial, name, context, helpers, partials, data, depths);

                if (result == null && env.compile) {
                    var options = { helpers: helpers, partials: partials, data: data, depths: depths };
                    partials[name] = env.compile(partial, { data: data !== undefined, compat: templateSpec.compat }, env);
                    result = partials[name](context, options);
                }
                if (result != null) {
                    if (indent) {
                        var lines = result.split('\n');
                        for (var i = 0, l = lines.length; i < l; i++) {
                            if (!lines[i] && i + 1 === l) {
                                break;
                            }

                            lines[i] = indent + lines[i];
                        }
                        result = lines.join('\n');
                    }
                    return result;
                } else {
                    throw new Exception("The partial " + name + " could not be compiled when running in runtime-only mode");
                }
            };

            // Just add water
            var container = {
                lookup: function(depths, name) {
                    var len = depths.length;
                    for (var i = 0; i < len; i++) {
                        if (depths[i] && depths[i][name] != null) {
                            return depths[i][name];
                        }
                    }
                },
                lambda: function(current, context) {
                    return typeof current === 'function' ? current.call(context) : current;
                },

                escapeExpression: Utils.escapeExpression,
                invokePartial: invokePartialWrapper,

                fn: function(i) {
                    return templateSpec[i];
                },

                programs: [],
                program: function(i, data, depths) {
                    var programWrapper = this.programs[i],
                        fn = this.fn(i);
                    if (data || depths) {
                        programWrapper = program(this, i, fn, data, depths);
                    } else if (!programWrapper) {
                        programWrapper = this.programs[i] = program(this, i, fn);
                    }
                    return programWrapper;
                },

                data: function(data, depth) {
                    while (data && depth--) {
                        data = data._parent;
                    }
                    return data;
                },
                merge: function(param, common) {
                    var ret = param || common;

                    if (param && common && (param !== common)) {
                        ret = Utils.extend({}, common, param);
                    }

                    return ret;
                },

                noop: env.VM.noop,
                compilerInfo: templateSpec.compiler
            };

            var ret = function(context, options) {
                options = options || {};
                var data = options.data;

                ret._setup(options);
                if (!options.partial && templateSpec.useData) {
                    data = initData(context, data);
                }
                var depths;
                if (templateSpec.useDepths) {
                    depths = options.depths ? [context].concat(options.depths) : [context];
                }

                return templateSpec.main.call(container, context, container.helpers, container.partials, data, depths);
            };
            ret.isTop = true;

            ret._setup = function(options) {
                if (!options.partial) {
                    container.helpers = container.merge(options.helpers, env.helpers);

                    if (templateSpec.usePartial) {
                        container.partials = container.merge(options.partials, env.partials);
                    }
                } else {
                    container.helpers = options.helpers;
                    container.partials = options.partials;
                }
            };

            ret._child = function(i, data, depths) {
                if (templateSpec.useDepths && !depths) {
                    throw new Exception('must pass parent depths');
                }

                return program(container, i, templateSpec[i], data, depths);
            };
            return ret;
        }