VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); ve.init(); VelocityContext context = new VelocityContext(); context.put("date", getMyTimestampFunction()); Template t = ve.getTemplate( "templates/email_html_new.vm" ); StringWriter writer = new StringWriter(); t.merge( context, writer );
@Override public String render(ModelAndView modelAndView) { Template template = velocityEngine.getTemplate(provider.layout(), "utf-8"); Object model = modelAndView.getModel(); if (model == null) { model = Collections.emptyMap(); } if (model instanceof Map) { VelocityContext context = initialContextProvider.getVelocityContext((Map) model, controller, modelAndView.getViewName()); StringWriter writer = new StringWriter(); template.merge(context, writer); Object meta = context.get("meta"); context.put("meta", GSON.toJson(meta)); return writer.toString(); } else { throw new IllegalArgumentException("modelAndView must be of type java.util.Map"); } } }
import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import java.io.StringWriter; public class TemplateExample { public static void main(String args[]) throws Exception { Velocity.init(); VelocityContext context = new VelocityContext(); context.put("name", "Mark"); context.put("invoiceNumber", "42123"); context.put("dueDate", "June 6, 2009"); String template = "Hello $name. Please find attached invoice" + " $invoiceNumber which is due on $dueDate."; StringWriter writer = new StringWriter(); Velocity.evaluate(context, writer, "TemplateName", template); System.out.println(writer); } }
/** * 融合模板和内容并写入到Writer * @param template 模板 * @param context 内容 * @param writer Writer */ public static void merge(Template template, VelocityContext context, Writer writer) { if(template == null) { throw new UtilException("Template is null"); } if(context == null) { context = new VelocityContext(globalContext); }else { //加入全局上下文 for (Entry<String, Object> entry : globalContext.entrySet()) { context.put(entry.getKey(), entry.getValue()); } } template.merge(context, writer); }
private String processHeaderTemplate(String templateName, Schema schema, String namespace) { VelocityContext context = new VelocityContext(); context.put("record_name", StyleUtils.toLowerUnderScore(schema.getName())); context.put("namespace", namespace); return generateSourceFromTemplate(TEMPLATE_DIR + File.separator + templateName, context); }
private static String applyToVelocityTemplate(String appMapURL, List<JenkinsAMChart> strategyCharts) { VelocityEngine ve = new VelocityEngine(); StringWriter writer = new StringWriter(); ve.setProperty("resource.loader", "classpath"); ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); ve.init(); Template t = ve.getTemplate("amHistogramChartsReport.vm"); VelocityContext context = new VelocityContext(); context.put("strategyCharts", strategyCharts); context.put("url", appMapURL); t.merge(context, writer); return writer.toString(); }
public String process(Map<String, Object> context, TemplateIdentifier templateIdentifier) { StringWriter stringWriter = new StringWriter(); VelocityContext velocityContext = new VelocityContext(context); try { velocityEngine.mergeTemplate(templateIdentifier.getFileName(), "UTF-8", velocityContext, stringWriter); return stringWriter.toString(); } catch (ResourceNotFoundException e) { LOGGER.error("", e); } catch (ParseErrorException e) { LOGGER.error("", e); } catch (MethodInvocationException e) { LOGGER.error("", e); } catch (Exception e) { LOGGER.error("", e); } return ""; }
@Override public Message prepare(Template template) throws MessageException { VelocityContext context = new VelocityContext(template.getData()); StringWriter writer = new StringWriter(); try { engine.evaluate(context, writer, "template", // I have no idea what this is used for template.getTemplate()); } catch (Exception e) { // need better error handling log.error("Failed to prepare message using template " + e.getMessage(), e); throw new MessageException(e); } // Prepare the message Message message = new Message(); message.setSubject(template.getSubject()); message.setRecipients(template.getRecipients()); message.setSender(template.getSender()); message.setContent(writer.toString()); return message; } }
gen.parse(); VelocityContext ctx = new VelocityContext(); ctx.put("resources", gen.getResources()); ctx.put("packageBase", configuration.getPackageBase()); ctx.put("version", configuration.getVersion()); ctx.put("package_suffix", configuration.getPackageSuffix()); ctx.put("esc", new EscapeTool()); ctx.put("resourcePackage", configuration.getResourcePackage()); ctx.put("versionCapitalized", configuration.getVersionCapitalized()); VelocityEngine v = new VelocityEngine(); v.setProperty("resource.loader", "cp"); v.setProperty("cp.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); v.setProperty("runtime.references.strict", Boolean.TRUE); OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(file, false), "UTF-8"); v.evaluate(ctx, w, "", templateReader); w.close();
OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(f, false), "UTF-8"); VelocityContext ctx = new VelocityContext(); InputStream templateIs = null; ctx.put("valueSet", theValueSetTm); ctx.put("packageBase", thePackageBase); ctx.put("esc", new EscapeTool()); v.evaluate(ctx, w, "", templateReader); w.close();
public void render(String template, Map<String, Object> map, OutputStream stream) { VelocityContext context = new VelocityContext(map); OutputStreamWriter writer = new OutputStreamWriter(stream); try { engine.mergeTemplate(baseTemplateDir + "/" + template, "UTF-8", context, writer); writer.flush(); } catch(Exception e) { throw new VoldemortException(e); } }
@Override public void writer(Map<String, Object> objectMap, String templatePath, String outputFile) throws Exception { if (StringUtils.isEmpty(templatePath)) { return; } Template template = velocityEngine.getTemplate(templatePath, ConstVal.UTF8); try (FileOutputStream fos = new FileOutputStream(outputFile); OutputStreamWriter ow = new OutputStreamWriter(fos, ConstVal.UTF8); BufferedWriter writer = new BufferedWriter(ow)) { template.merge(new VelocityContext(objectMap), writer); } logger.debug("模板:" + templatePath + "; 文件:" + outputFile); }
private void generateReport() { context.put("report_file", getWebPage()); Template template = engine.getTemplate("templates/generators/" + templateFileName); File reportFile = new File(configuration.getReportDirectory(), ReportBuilder.BASE_DIRECTORY + File.separatorChar + getWebPage()); try (Writer writer = new OutputStreamWriter(new FileOutputStream(reportFile), StandardCharsets.UTF_8)) { template.merge(context, writer); } catch (IOException e) { throw new ValidationException(e); } }
private byte[] process(byte[] input, PropertyResolver props) throws IOException { try { VelocityContext context = new VelocityContext(); context.put("context", props); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Writer writer = new OutputStreamWriter(baos); Velocity.evaluate(context, writer, "", new InputStreamReader(new ByteArrayInputStream(input))); writer.flush(); return baos.toByteArray(); } catch (IOException ioe) { throw new IOException("Error processing the artifact: " + ioe.getMessage()); } }
VelocityContext ctx = new VelocityContext(); ctx.put("includeDescriptionAnnotations", true); ctx.put("packageBase", thePackageBase); ctx.put("package_suffix", packageSuffix); ctx.put("hash", "#"); ctx.put("imports", imports); ctx.put("profile", theResource.getProfile()); ctx.put("version", myVersion.replace(".", "")); ctx.put("versionEnumName", determineVersionEnum().name()); ctx.put("id", StringUtils.defaultString(theResource.getId())); if (theResource.getDeclaringClassNameComplete() != null) { ctx.put("className", theResource.getDeclaringClassNameComplete()); } else { ctx.put("className", (theResource.getName())); ctx.put("elementName", theResource.getElementName()); ctx.put("classNameComplete", (theResource.getName()) + getFilenameSuffix()); // HumanNameDt ctx.put("shortName", defaultString(theResource.getShortName())); ctx.put("definition", defaultString(theResource.getDefinition())); ctx.put("requirements", defaultString(theResource.getRequirement())); ctx.put("children", theResource.getChildren()); ctx.put("resourceBlockChildren", theResource.getResourceBlockChildren()); ctx.put("childExtensionTypes", ObjectUtils.defaultIfNull(myExtensions, new ArrayList<Extension>())); ctx.put("searchParams", (theResource.getSearchParameters())); ctx.put("searchParamsReference", (theResource.getSearchParametersResource())); ctx.put("searchParamsWithoutComposite", (theResource.getSearchParametersWithoutComposite())); ctx.put("includes", (theResource.getIncludes())); ctx.put("esc", new EscapeTool()); ctx.put("isRi", determineVersionEnum().isRi());
/** * 处理外部pagelet */ public void processTempleate(Context context, Writer writer, String path) throws Exception { TinyVelocityContext tinyVelocityContext = new TinyVelocityContext( context); if (initContext != null) { context.putSubContext(BASE_CONTEXT, initContext); } VelocityContext velocityContext = new VelocityContext( tinyVelocityContext); String templatePath = findTemplatePath(path); Template template = velocity.getTemplate(templatePath, ENCODING); template.merge(velocityContext, writer, macroList); writer.flush(); }
VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); ve.init(); final String templatePath = "templates/" + templateName + ".vm"; InputStream input = this.getClass().getClassLoader().getResourceAsStream(templatePath); if (input == null) { throw new IOException("Template file doesn't exist"); } InputStreamReader reader = new InputStreamReader(input); VelocityContext context = new VelocityContext(); if (properties != null) { stringfyNulls(properties); for (Map.Entry<String, Object> property : properties.entrySet()) { context.put(property.getKey(), property.getValue()); } } Template template = ve.getTemplate(templatePath, "UTF-8"); String outFileName = File.createTempFile("report", ".html").getAbsolutePath(); BufferedWriter writer = new BufferedWriter(new FileWriter(new File(outFileName))); if (!ve.evaluate(context, writer, templatePath, reader)) { throw new Exception("Failed to convert the template into html."); } template.merge(context, writer); writer.flush(); writer.close();
protected void postEncode(final MessageContext<SAMLObject> messageContext, final String endpointURL) throws MessageEncodingException { log.debug("Invoking Velocity template to create POST body"); try { final VelocityContext velocityContext = new VelocityContext(); this.populateVelocityContext(velocityContext, messageContext, endpointURL); responseAdapter.setContentType("text/html"); responseAdapter.init(); final OutputStreamWriter out = responseAdapter.getOutputStreamWriter(); this.getVelocityEngine().mergeTemplate(this.getVelocityTemplateId(), "UTF-8", velocityContext, out); out.flush(); } catch (Exception e) { throw new MessageEncodingException("Error creating output document", e); } }
final VelocityEngine ve = new VelocityEngine(); p.toString())); ve.init(p); final Context context = new VelocityContext(); context.put("catalog", catalog); context.put("identifiers", identifiers); templateLocation, templateEncoding)); final Template template = ve.getTemplate(templateLocation, templateEncoding); template.merge(context, writer);
/** * 将Map转为VelocityContext * * @param bindingMap 参数绑定的Map * @return {@link VelocityContext} */ private VelocityContext toContext(Map<?, ?> bindingMap) { return new VelocityContext(bindingMap); }