Evaluates a template string, e.g. "Hello @contact.name you have @(contact.reports * 2) reports"
@param template the template string
@param context the evaluation context
@return a tuple of the evaluated template and a list of evaluation errors
775708
public EvaluatedTemplate evaluateTemplate(String template, EvaluationContext context) {
        return evaluateTemplate(template, context, false);
    }
614722
public static AppMethodInfo[] getAppMethodsCalled(String basePath, final String templateName,
            final String contextClass) {

        final HashMap<AppMethodInfo, AppMethodInfo> methodsCalledMap =
            new HashMap<AppMethodInfo, AppMethodInfo>();

        try {
            File templatePath = new File(new File(basePath),
                templateName.replace('.', '/') + ".class");
            if (!templatePath.exists() &&
                    templateName.startsWith(TEMPLATE_PACKAGE)) {
                templatePath = new File(new File(basePath),
                    templateName.substring(TEMPLATE_PACKAGE.length()).
                    replace('.','/') + ".class");
            }

            final MethodInfo executeMethod = getTemplateExecuteMethod(new FileInputStream(templatePath));

            CodeDisassembler cd = new CodeDisassembler(executeMethod);
            cd.disassemble(new CodeAssemblerPrinter(executeMethod
                .getMethodDescriptor().getParameterTypes(), true, null) {

                 public void invokeVirtual(String className, String methodName,
                         TypeDesc ret, TypeDesc[] params)  {
                     if ("print".equals(methodName) ||
                             "toString".equals(methodName) ||
                             "equals".equals(methodName) ||
                             (contextClass.indexOf(className) == -1 &&
                             className.indexOf("MergedClass") == -1))
                         return;

                     AppMethodInfo ami = new AppMethodInfo(methodName, params);
                     if (! methodsCalledMap.containsKey(ami))
                         methodsCalledMap.put(ami, ami);
                     else
                         methodsCalledMap.get(ami).incCallCount();
                 }

                 public void println(String s) { } // Do nothing
            });

            final MethodInfo substituteMethod = getTemplateSubstituteMethod(new FileInputStream(templatePath));

            if (substituteMethod == null)
                return methodsCalledMap.values().toArray(
                    new AppMethodInfo[methodsCalledMap.values().size()]);

            // check the substitute methods on this template
            cd = new CodeDisassembler(substituteMethod);
            cd.disassemble(new CodeAssemblerPrinter(substituteMethod
                .getMethodDescriptor().getParameterTypes(), true, null) {

                 public void invokeVirtual(String className, String methodName,
                         TypeDesc ret, TypeDesc[] params)  {
                     if ("print".equals(methodName) ||
                             "toString".equals(methodName) ||
                             "equals".equals(methodName) ||
                             (contextClass.indexOf(className) == -1 &&
                             className.indexOf("MergedClass") == -1))
                         return;

                     AppMethodInfo ami = new AppMethodInfo(methodName, params);
                     if (! methodsCalledMap.containsKey(ami))
                         methodsCalledMap.put(ami, ami);
                     else
                         methodsCalledMap.get(ami).incCallCount();
                 }

                 public void println(String s) { } // Do nothing
            });
        }
        catch (IOException ix) {
            return new AppMethodInfo[0];
        }

        return methodsCalledMap.values().toArray(
            new AppMethodInfo[methodsCalledMap.values().size()]);
    }
1326185
public static <T extends Comparable<?>> ComparableTemplate<T> comparableTemplate(Class<? extends T> cl, String template, List<?> args) {
        return comparableTemplate(cl, createTemplate(template), args);
    }
356936
public JsonResponse deleteTemplate(String template) throws IOException {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put(Template.PARAM_TEMPLATE, template);
        return apiDelete(ApiAction.template, data);
    }
789274
protected FunctionTemplate getFunctionTemplate(final List<FunctionTemplate> templates) throws Exception {
        info("");
        info(FIND_TEMPLATE);

        if (settings != null && !settings.isInteractiveMode()) {
            assureInputInBatchMode(getFunctionTemplate(),
                str -> getTemplateNames(templates)
                    .stream()
                    .filter(Objects::nonNull)
                    .anyMatch(o -> o.equalsIgnoreCase(str)),
                this::setFunctionTemplate,
                true);
        } else {
            assureInputFromUser("template for new function",
                getFunctionTemplate(),
                getTemplateNames(templates),
                this::setFunctionTemplate);
        }

        return findTemplateByName(templates, getFunctionTemplate());
    }
348704
public Template getTemplate(String name, Locale locale, Object args) throws IOException, ParseException {
        if (args instanceof String)
            return getTemplate(name, locale, (String) args);
        return getTemplate(name, locale, null, args);
    }
901050
public static String template(final String template, final Object root)
	{
		StrSubstitutor substitutor = new StrSubstitutor(newOgnlLookup(root));

		return substitutor.replace(template);
	}
15534
def _TemplateExists(unused_value, context, args):
    """"""
    try:
        name = args[0]
    except IndexError:
        raise EvaluationError('The "template" predicate requires an argument.')
    return context.HasTemplate(name)
1019458
public static <T> DslTemplate<T> dslTemplate(Class<? extends T> cl, String template, List<?> args) {
        return dslTemplate(cl, createTemplate(template), args);
    }
69742
protected InputStream getTemplateAsStream(TestContext context) {
        Resource resource;
        if (templateResource != null) {
            resource = templateResource;
        } else {
            resource = FileUtils.getFileResource(template, context);
        }

        String templateYml;
        try {
            templateYml = context.replaceDynamicContentInString(FileUtils.readToString(resource));
        } catch (IOException e) {
            throw new CitrusRuntimeException("Failed to read template resource", e);
        }
        return new ByteArrayInputStream(templateYml.getBytes());
    }
1201580
public Template getTemplate(String templateId) throws HelloSignException {
        String url = BASE_URI + TEMPLATE_URI + "/" + templateId;
        return new Template(httpClient.withAuth(auth).get(url).asJson());
    }
381328
public void invokeTemplate(int line, String name, ITemplate caller, ITag.__ParameterList params, ITag.__Body body, ITag.__Body context, boolean ignoreNonExistsTag) {
        if (_nonExistsTags.contains(name)) return;

        Sandbox.enterSafeZone(secureCode);
        RythmEvents.ENTER_INVOKE_TEMPLATE.trigger(this, (TemplateBase) caller);
        try {
            // try tag registry first
            ITemplate t = _tags.get(name);
            if (null == t) {
                t = _templates.get(name);
            }
            if (null == t && S.isEqual(name, caller.__getName())) {
                // is calling self
                t = caller;
            }

            if (null == t) {
                // try imported path
                TemplateClass tc = caller.__getTemplateClass(true);
                if (null != tc.importPaths) {
                    for (String s : tc.importPaths) {
                        if (s.startsWith("java")) {
                            continue;
                        }
                        String name0 = s + "." + name;
                        t = _tags.get(name0);
                        if (null == t) t = _templates.get(name0);
                        if (null != t) break;
                    }
                }

                // try relative path
                if (null == t) {
                    String callerName = tc.getTagName();
                    int pos = -1;
                    if (null != callerName) pos = callerName.lastIndexOf(".");
                    if (-1 != pos) {
                        String name0 = callerName.substring(0, pos) + "." + name;
                        t = _tags.get(name0);
                        if (null == t) t = _templates.get(name0);
                    }
                }

                // try load the tag from resource
                if (null == t) {
                    tc = resourceManager().tryLoadTemplate(name, tc, caller.__curCodeType());
                    if (null != tc) t = _templates.get(tc.getTagName());
                    if (null == t) {
                        if (ignoreNonExistsTag) {
                            if (logger.isDebugEnabled()) {
                                logger.debug("cannot find tag: " + name);
                            }
                            _nonExistsTags.add(name);
                            if (isDevMode() && nonExistsTemplatesChecker == null) {
                                nonExistsTemplatesChecker = new NonExistsTemplatesChecker();
                            }
                            return;
                        } else {
                            throw new NullPointerException("cannot find tag: " + name);
                        }
                    }
                    t = t.__cloneMe(this, caller);
                }
            }

            if (!(t instanceof JavaTagBase)) {
                // try refresh the tag loaded from template file under tag root
                // note Java source tags are not reloaded here
                String cn = t.getClass().getName();
                TemplateClass tc0 = classes().getByClassName(cn);
                if (null == tc0) {
                    throw new NullPointerException(String.format("null tc0 found. t.class: %s, name: %s, caller.class: %s", cn, name, caller.getClass()));
                }
                t = tc0.asTemplate(caller, this);
            } else {
                t = t.__cloneMe(this, caller);
            }

            if (null != params) {
                if (t instanceof JavaTagBase) {
                    ((JavaTagBase) t).__setRenderArgs0(params);
                } else {
                    for (int i = 0; i < params.size(); ++i) {
                        ITag.__Parameter param = params.get(i);
                        if (null != param.name) t.__setRenderArg(param.name, param.value);
                        else t.__setRenderArg(i, param.value);
                    }
                }
            }
            if (null == body && null != params) {
                body = (ITag.__Body) params.getByName("__body");
                if (null == body) {
                    body = (ITag.__Body) params.getByName("_body");
                }
            }
            if (null != body) {
                t.__setRenderArg("__body", body);
                t.__setRenderArg("_body", body); // for compatibility
            }
            RythmEvents.ON_TAG_INVOCATION.trigger(this, F.T2((TemplateBase) caller, t));
            try {
                if (null != context) {
                    t.__setBodyContext(context);
                }
                t.__setSecureCode(secureCode).__call(line);
            } finally {
                RythmEvents.TAG_INVOKED.trigger(this, F.T2((TemplateBase) caller, t));
            }
        } finally {
            RythmEvents.EXIT_INVOKE_TEMPLATE.trigger(this, (TemplateBase) caller);
            Sandbox.leaveCurZone(secureCode);
        }
    }
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)
1007339
public TemplateModel parseStandalone(
            final ITemplateContext context, final String template, final Set<String> templateSelectors,
            final TemplateMode templateMode, final boolean useCache, final boolean failIfNotExists) {

        Validate.notNull(context, "Context cannot be null");
        Validate.notNull(template, "Template cannot be null");
        // templateSelectors CAN be null if we are going to render the entire template
        // templateMode CAN be null if we are going to use the mode specified by the template resolver
        // templateResolutionAttributes CAN be null


        final String ownerTemplate = context.getTemplateData().getTemplate();
        final Map<String,Object> templateResolutionAttributes = context.getTemplateResolutionAttributes();

        final Set<String> cleanTemplateSelectors;
        if (templateSelectors != null && !templateSelectors.isEmpty()) {
            Validate.containsNoEmpties(
                    templateSelectors, "If specified, the Template Selector set cannot contain any nulls or empties");
            if (templateSelectors.size() == 1) {
                cleanTemplateSelectors = Collections.singleton(templateSelectors.iterator().next());
            } else {
                // We will be using a TreeSet because we want the selectors to be ORDERED, so that comparison at the
                // equals(...) method works alright
                cleanTemplateSelectors = Collections.unmodifiableSet(new TreeSet<String>(templateSelectors));
            }
        } else {
            cleanTemplateSelectors = null;
        }


        final TemplateCacheKey cacheKey =
                useCache?
                        new TemplateCacheKey(
                                ownerTemplate,
                                template, cleanTemplateSelectors,
                                0, 0,
                                templateMode,
                                templateResolutionAttributes)
                        : null;

        /*
         * First look at the cache - it might be already cached
         */
        if (useCache && this.templateCache != null) {
            final TemplateModel cached =  this.templateCache.get(cacheKey);
            if (cached != null) {
                /*
                 * Just at the end, and importantly AFTER CACHING, check if we need to apply any pre-processors
                 * to this model before returning and letting the engine insert the model in any way it needs.
                 */
                return applyPreProcessorsIfNeeded(context, cached);
            }
        }


        /*
         * Resolve the template
         */
        final TemplateResolution templateResolution =
                resolveTemplate(this.configuration, ownerTemplate, template, templateResolutionAttributes, failIfNotExists);


        /*
         * Once the template has been resolved (or tried to), and depending on the value of our 'failIfNotExists'
         * flag, we will check two conditions in which we will be returning null:
         *
         *    1. No template resolver has been able to resolve the template (this can happen if resolvers are
         *       configured with the 'checkExistence' flag to true).
         *    2. If the template was resolved, its existence should be checked in order to avoid exceptions during
         *       the reading phase.
         *
         * NOTE we will not cache this "null" result because the fact that a template is cacheable or not is
         * determined by template resolvers. And in this case there is no template resolver being applied
         * (actually, we are here because no resolver had success).
         */
        if (!failIfNotExists) {

            if (templateResolution == null) {
                // No resolver could resolve this
                return null;
            }

            if (!templateResolution.isTemplateResourceExistenceVerified()) {
                final ITemplateResource resource = templateResolution.getTemplateResource();
                if (resource == null || !resource.exists()) {
                    // Calling resource.exists() each time is not great, but think this only happens if the resource
                    // has not been cached (e.g. when it does not exist)
                    return null;
                }
            }

        }


        /*
         * Build the TemplateData object
         */
        final TemplateData templateData =
                buildTemplateData(templateResolution, template, cleanTemplateSelectors, templateMode, useCache);


        /*
         *  Create the Template Handler that will be in charge of building the TemplateModel
         */
        final ModelBuilderTemplateHandler builderHandler = new ModelBuilderTemplateHandler(this.configuration, templateData);


        /*
         * PROCESS THE TEMPLATE
         */
        final ITemplateParser parser = getParserForTemplateMode(templateData.getTemplateMode());
        parser.parseStandalone(
                this.configuration,
                ownerTemplate, template, cleanTemplateSelectors, templateData.getTemplateResource(),
                templateData.getTemplateMode(), templateResolution.getUseDecoupledLogic(), builderHandler);

        final TemplateModel templateModel = builderHandler.getModel();


        /*
         * Cache the template if it is cacheable
         */
        if (useCache && this.templateCache != null) {
            if (templateResolution.getValidity().isCacheable()) {
                this.templateCache.put(cacheKey, templateModel);
            }
        }


        /*
         * Last step: just at the end, and importantly AFTER CACHING, check if we need to apply any pre-processors
         * to this model before returning and letting the engine insert the model in any way it needs.
         */
        return applyPreProcessorsIfNeeded(context, templateModel);

    }
198342
def _render_context(self, template, block, **context):
        
        return u''.join(block(template.new_context(context)))
835620
def parse_template(self, template, **context):
        
        required_blocks = ["subject", "body"]
        optional_blocks = ["text_body", "html_body", "return_path", "format"]

        if self.template_context:
            context = dict(self.template_context.items() + context.items())
        blocks = self.template.render_blocks(template, **context)

        for rb in required_blocks:
            if rb not in blocks:
                raise AttributeError("Template error: block '%s' is missing from '%s'" % (rb, template))

        mail_params = {
            "subject": blocks["subject"].strip(),
            "body": blocks["body"]
        }
        for ob in optional_blocks:
            if ob in blocks:
                if ob == "format" and mail_params[ob].lower() not in ["html", "text"]:
                    continue
                mail_params[ob] = blocks[ob]
        return mail_params
264201
function (f, data, context) {
    try {
        return _.template(data)(context);
    } catch(e) {
        log('error', 'could not parse template file', f);
        throw(e);
    }
}