freemarker.template.Template.process()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(14.1k)|赞(0)|评价(0)|浏览(1666)

本文整理了Java中freemarker.template.Template.process()方法的一些代码示例,展示了Template.process()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Template.process()方法的具体详情如下:
包路径:freemarker.template.Template
类名称:Template
方法名:process

Template.process介绍

[英]Executes template, using the data-model provided, writing the generated output to the supplied Writer.

For finer control over the runtime environment setup, such as per-HTTP-request configuring of FreeMarker settings, you may need to use #createProcessingEnvironment(Object,Writer) instead.
[中]使用提供的数据模型执行模板,将生成的输出写入提供的编写器。
为了更好地控制运行时环境设置,例如根据HTTP请求配置FreeMarker设置,您可能需要使用#createProcessingEnvironment(Object,Writer)。

代码示例

代码示例来源:origin: baomidou/mybatis-plus

@Override
public void writer(Map<String, Object> objectMap, String templatePath, String outputFile) throws Exception {
  Template template = configuration.getTemplate(templatePath);
  try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {
    template.process(objectMap, new OutputStreamWriter(fileOutputStream, ConstVal.UTF8));
  }
  logger.debug("模板:" + templatePath + ";  文件:" + outputFile);
}

代码示例来源:origin: DeemOpen/zkui

public void renderError(HttpServletRequest request, HttpServletResponse response, String error) {
  try {
    logger.error("Error :" + error);
    Map<String, Object> templateParam = new HashMap<>();
    response.setContentType("text/html;charset=UTF-8");
    Template template = null;
    Configuration config = new Configuration();
    config.setClassForTemplateLoading(request.getServletContext().getClass(), "/");
    template = config.getTemplate("/webapp/template/error.ftl.html");
    templateParam.put("error", error);
    template.process(templateParam, response.getWriter());
  } catch (TemplateException | IOException ex) {
    logger.error(Arrays.toString(ex.getStackTrace()));
  }
}

代码示例来源:origin: jfinal/jfinal

@SuppressWarnings({"unchecked", "rawtypes"})
  public void render() {
    response.setContentType(getContentType());
    
    Map data = new HashMap();
    for (Enumeration<String> attrs=request.getAttributeNames(); attrs.hasMoreElements();) {
      String attrName = attrs.nextElement();
      data.put(attrName, request.getAttribute(attrName));
    }
    
    PrintWriter writer = null;
    try {
      Template template = config.getTemplate(view);
      writer = response.getWriter();
      template.process(data, writer);		// Merge the data-model and the template
    } catch (Exception e) {
      throw new RenderException(e);
    }
  }
}

代码示例来源:origin: spotify/apollo

/**
 * Call the template engine and return the result.
 *
 * @param templateName The template name, respective to the "resources" folder
 * @param object       The parameter to pass to the template
 * @param <T>          The Type of the parameters
 * @return The HTML
 */
public static <T> ByteString serialize(final String templateName, T object) {
 StringWriter templateResults = new StringWriter();
 try {
  final Template template = configuration.getTemplate(templateName);
  template.process(object, templateResults);
 } catch (Exception e) {
  throw Throwables.propagate(e);
 }
 return ByteString.encodeUtf8(templateResults.toString());
}

代码示例来源:origin: org.freemarker/freemarker

/**
 * Performs the transformation.
 */
void transform() throws Exception {
  String templateName = ftlFile.getName();
  Template template = cfg.getTemplate(templateName, locale);
  NodeModel rootNode = NodeModel.parse(inputFile);
  OutputStream outputStream = System.out;
  if (outputFile != null) {
    outputStream = new FileOutputStream(outputFile);
  }
  Writer outputWriter = new OutputStreamWriter(outputStream, encoding);
  try {
    template.process(null, outputWriter, null, rootNode);
  } finally {
    if (outputFile != null)
      outputWriter.close();
  }
}

代码示例来源:origin: allure-framework/allure2

@Override
public void aggregate(final Configuration configuration,
           final List<LaunchResults> launchesResults,
           final Path outputDirectory) throws IOException {
  final FreemarkerContext context = configuration.requireContext(FreemarkerContext.class);
  final Path exportFolder = Files.createDirectories(outputDirectory.resolve(Constants.EXPORT_DIR));
  final Path mailFile = exportFolder.resolve("mail.html");
  try (BufferedWriter writer = Files.newBufferedWriter(mailFile)) {
    final Template template = context.getValue().getTemplate("mail.html.ftl");
    template.process(new HashMap<>(), writer);
  } catch (TemplateException e) {
    LOGGER.error("Could't write mail file", e);
  }
}

代码示例来源:origin: Graylog2/graylog2-server

private String renderTemplate(String configurationId, Map<String, Object> sidecarContext) throws RenderTemplateException {
    Writer writer = new StringWriter();
    String template;

    final Map<String, Object> context = new HashMap<>();
    context.put("sidecar", sidecarContext);

    final Map<String, Object> userContext =
        configurationVariableService.all().stream().collect(Collectors.toMap(ConfigurationVariable::name, ConfigurationVariable::content));
    context.put(ConfigurationVariable.VARIABLE_PREFIX, userContext);

    try {
      Template compiledTemplate = templateConfiguration.getTemplate(configurationId);
      compiledTemplate.process(context, writer);
    } catch (TemplateException e) {
      LOG.error("Failed to render template: " + e.getMessageWithoutStackTop());
      throw new RenderTemplateException(e.getFTLInstructionStack(), e);
    } catch (IOException e) {
      LOG.error("Failed to render template: ", e);
      throw new RenderTemplateException(e.getMessage(), e);
    }

    template = writer.toString();
    return template.endsWith("\n") ? template : template + "\n";
  }
}

代码示例来源:origin: allure-framework/allure2

protected void writeIndexHtml(final Configuration configuration,
               final Path outputDirectory) throws IOException {
  final FreemarkerContext context = configuration.requireContext(FreemarkerContext.class);
  final Path indexHtml = outputDirectory.resolve("index.html");
  final List<PluginConfiguration> pluginConfigurations = configuration.getPlugins().stream()
      .map(Plugin::getConfig)
      .collect(Collectors.toList());
  try (BufferedWriter writer = Files.newBufferedWriter(indexHtml)) {
    final Template template = context.getValue().getTemplate("index.html.ftl");
    final Map<String, Object> dataModel = new HashMap<>();
    dataModel.put(Constants.PLUGINS_DIR, pluginConfigurations);
    template.process(dataModel, writer);
  } catch (TemplateException e) {
    LOGGER.error("Could't write index file", e);
  }
}

代码示例来源:origin: DeemOpen/zkui

public void renderHtml(HttpServletRequest request, HttpServletResponse response, Map<String, Object> templateParam, String view) throws IOException, TemplateException {
  if (request != null && response != null && templateParam != null) {
    //There is no way to access session info in freemarker template. 
    //Hence all view rendering happens via this function which adds session info to attribute for each request.
    HttpSession session = request.getSession();
    if (session != null) {
      //Flash messages are always set at session level and need to be propgrated to attributes.
      //They are reset after being displayed once.
      if (session.getAttribute("flashMsg") != null) {
        templateParam.put("flashMsg", session.getAttribute("flashMsg"));
        session.setAttribute("flashMsg", null);
      }
      templateParam.put("authName", session.getAttribute("authName"));
      templateParam.put("authRole", session.getAttribute("authRole"));
      response.setContentType("text/html;charset=UTF-8");
      
      Template template = null;
      long startTime = System.currentTimeMillis();
      Configuration config = new Configuration();
      config.setClassForTemplateLoading(request.getServletContext().getClass(), "/");
      template = config.getTemplate("/webapp/template/" + view);
      template.process(templateParam, response.getWriter());
      long estimatedTime = System.currentTimeMillis() - startTime;
      logger.trace("Elapsed Time in Secs for Rendering: " + estimatedTime / 1000);
    }
  }
}

代码示例来源:origin: dropwizard/dropwizard

@Override
public void render(View view,
          Locale locale,
          OutputStream output) throws IOException {
  final Configuration configuration = configurationCache.get(view.getClass());
  if (configuration == null) {
    throw new ViewRenderException("Couldn't find view class " + view.getClass());
  }
  try {
    final Charset charset = view.getCharset().orElseGet(() -> Charset.forName(configuration.getEncoding(locale)));
    final Template template = configuration.getTemplate(view.getTemplateName(), locale, charset.name());
    template.process(view, new OutputStreamWriter(output, template.getEncoding()));
  } catch (Exception e) {
    throw new ViewRenderException(e);
  }
}

代码示例来源:origin: kiegroup/optaplanner

private void writeHtmlOverviewFile() {
  File benchmarkReportDirectory = plannerBenchmarkResult.getBenchmarkReportDirectory();
  WebsiteResourceUtils.copyResourcesTo(benchmarkReportDirectory);
  htmlOverviewFile = new File(benchmarkReportDirectory, "index.html");
  Configuration freemarkerCfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
  freemarkerCfg.setDefaultEncoding("UTF-8");
  freemarkerCfg.setLocale(locale);
  freemarkerCfg.setClassForTemplateLoading(BenchmarkReport.class, "");
  String templateFilename = "benchmarkReport.html.ftl";
  Map<String, Object> model = new HashMap<>();
  model.put("benchmarkReport", this);
  model.put("reportHelper", new ReportHelper());
  try (Writer writer = new OutputStreamWriter(new FileOutputStream(htmlOverviewFile), "UTF-8")) {
    Template template = freemarkerCfg.getTemplate(templateFilename);
    template.process(model, writer);
  } catch (IOException e) {
    throw new IllegalArgumentException("Can not read templateFilename (" + templateFilename
        + ") or write htmlOverviewFile (" + htmlOverviewFile + ").", e);
  } catch (TemplateException e) {
    throw new IllegalArgumentException("Can not process Freemarker templateFilename (" + templateFilename
        + ") to htmlOverviewFile (" + htmlOverviewFile + ").", e);
  }
}

代码示例来源:origin: geoserver/geoserver

@Test
  public void testFeatureSequence() throws Exception {
    Template template = cfg.getTemplate("FeatureSequence.ftl");

    StringWriter out = new StringWriter();
    template.process(features, out);

    assertEquals(
        "three\none\n3", out.toString().replaceAll("\r\n", "\n").replaceAll("\r", "\n"));
  }
}

代码示例来源:origin: geoserver/geoserver

@Test
public void testFeatureCollection() throws Exception {
  Template template = cfg.getTemplate("FeatureCollection.ftl");
  StringWriter out = new StringWriter();
  template.process(features, out);
  assertEquals(
      "fid.1\nfid.2\nfid.3\n",
      out.toString().replaceAll("\r\n", "\n").replaceAll("\r", "\n"));
}

代码示例来源:origin: geoserver/geoserver

@Test
public void testFeatureDynamic() throws Exception {
  Template template = cfg.getTemplate("FeatureDynamic.ftl");
  StringWriter out = new StringWriter();
  template.process(features.iterator().next(), out);
  // replace ',' with '.' for locales which use a comma for decimal point
  assertEquals(
      "string=one\nint=1\ndouble=1.1\ngeom=POINT (1 1)\n",
      out.toString().replace(',', '.').replaceAll("\r\n", "\n").replaceAll("\r", "\n"));
}

代码示例来源:origin: geoserver/geoserver

@Test
public void testFeatureSimple() throws Exception {
  Template template = cfg.getTemplate("FeatureSimple.ftl");
  StringWriter out = new StringWriter();
  template.process(features.iterator().next(), out);
  // replace ',' with '.' for locales which use a comma for decimal point
  assertEquals(
      "one\n1\n1.1\nPOINT (1 1)",
      out.toString().replace(',', '.').replaceAll("\r\n", "\n").replaceAll("\r", "\n"));
}

代码示例来源:origin: ninjaframework/ninja

freemarkerTemplate = cfg.getTemplate(templateName);
freemarkerTemplate.process(map, buffer);

代码示例来源:origin: shopizer-ecommerce/shopizer

Template textTemplate = freemarkerMailConfiguration.getTemplate(new StringBuilder(TEMPLATE_PATH).append("").append("/").append(tmpl).toString());
final StringWriter textWriter = new StringWriter();
try {
  textTemplate.process(templateTokens, textWriter);
} catch (TemplateException e) {
  throw new MailPreparationException(
BodyPart htmlPage = new MimeBodyPart();
freemarkerMailConfiguration.setClassForTemplateLoading(HtmlEmailSenderImpl.class, "/");
Template htmlTemplate = freemarkerMailConfiguration.getTemplate(new StringBuilder(TEMPLATE_PATH).append("").append("/").append(tmpl).toString());
final StringWriter htmlWriter = new StringWriter();
try {
  htmlTemplate.process(templateTokens, htmlWriter);
} catch (TemplateException e) {
  throw new MailPreparationException(

代码示例来源:origin: internetarchive/heritrix3

protected void writeHtml(Writer writer) {
    String baseRef = getRequest().getResourceRef().getBaseRef().toString();
    if(!baseRef.endsWith("/")) {
      baseRef += "/";
    }
    Configuration tmpltCfg = getTemplateConfiguration();

    ViewModel viewModel = new ViewModel();
    viewModel.setFlashes(Flash.getFlashes(getRequest()));
    viewModel.put("baseRef",baseRef);
    viewModel.put("model",makeDataModel());

    try {
      Template template = tmpltCfg.getTemplate("Beans.ftl");
      template.process(viewModel, writer);
      writer.flush();
    } catch (IOException e) { 
      throw new RuntimeException(e); 
    } catch (TemplateException e) { 
      throw new RuntimeException(e); 
    }
    
  }
}

代码示例来源:origin: internetarchive/heritrix3

protected void writeHtml(Writer writer) {
  EngineModel model = makeDataModel();
  String baseRef = getRequest().getResourceRef().getBaseRef().toString();
  if(!baseRef.endsWith("/")) {
    baseRef += "/";
  }
  Configuration tmpltCfg = getTemplateConfiguration();
  ViewModel viewModel = new ViewModel();
  viewModel.setFlashes(Flash.getFlashes(getRequest()));
  viewModel.put("baseRef",baseRef);
  viewModel.put("fileSeparator", File.separator);
  viewModel.put("engine", model);
  try {
    Template template = tmpltCfg.getTemplate("Engine.ftl");
    template.process(viewModel, writer);
    writer.flush();
  } catch (IOException e) { 
    throw new RuntimeException(e); 
  } catch (TemplateException e) { 
    throw new RuntimeException(e); 
  }
}

代码示例来源:origin: internetarchive/heritrix3

protected void writeHtml(Writer writer) {
  String baseRef = getRequest().getResourceRef().getBaseRef().toString();
  if(!baseRef.endsWith("/")) {
    baseRef += "/";
  }
  Configuration tmpltCfg = getTemplateConfiguration();
  ViewModel viewModel = new ViewModel();
  viewModel.setFlashes(Flash.getFlashes(getRequest()));
  viewModel.put("baseRef",baseRef);
  viewModel.put("job", makeDataModel());
  viewModel.put("heapReport", getEngine().heapReportData());
  try {
    Template template = tmpltCfg.getTemplate("Job.ftl");
    template.process(viewModel, writer);
    writer.flush();
  } catch (IOException e) { 
    throw new RuntimeException(e); 
  } catch (TemplateException e) { 
    throw new RuntimeException(e); 
  }
  
}

相关文章

微信公众号

最新文章

更多

Template类方法