Java Code Examples for org.thymeleaf.TemplateEngine#process()

The following examples show how to use org.thymeleaf.TemplateEngine#process() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TemplateUtilsTest.java    From SkaETL with Apache License 2.0 6 votes vote down vote up
@Test
public void astext() {

    StringTemplateResolver templateResolver = new StringTemplateResolver();
    templateResolver.setOrder(1);
    templateResolver.setTemplateMode(TemplateMode.TEXT);
    // TODO Cacheable or Not ?
    templateResolver.setCacheable(false);
    TemplateEngine templateEngine = new TemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);

    Context context = new Context();

    context.setVariable("mavar","cela");
    String process = templateEngine.process("ceci [[${mavar}]]", context);
    assertThat(process).isEqualTo("ceci cela");

    String notInterpreted = templateEngine.process("ceci <span th:text=\"${mavar}\"></span>", context);
    assertThat(notInterpreted).isEqualTo("ceci <span th:text=\"${mavar}\"></span>");
}
 
Example 2
Source File: TemplateUtilsTest.java    From SkaETL with Apache License 2.0 6 votes vote down vote up
@Test
public void ashtml() {

    StringTemplateResolver templateResolver = new StringTemplateResolver();
    templateResolver.setOrder(1);
    templateResolver.setTemplateMode(TemplateMode.HTML);
    // TODO Cacheable or Not ?
    templateResolver.setCacheable(false);
    TemplateEngine templateEngine = new TemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);

    Context context = new Context();

    context.setVariable("mavar","cela");
    String process = templateEngine.process("ceci [[${mavar}]]", context);
    assertThat(process).isEqualTo("ceci cela");

    String variant = templateEngine.process("ceci <span th:text=\"${mavar}\"></span>", context);
    assertThat(variant).isEqualTo("ceci <span>cela</span>");
}
 
Example 3
Source File: MailService.java    From tutorial with MIT License 6 votes vote down vote up
private String getMailBodyFromTemplate(String templateName, Map<String, Object> vars){
    ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
    resolver.setPrefix("email-templates/");     //模板所在目录,相对于当前classloader的classpath。
    resolver.setSuffix(".html");                //模板文件后缀
    TemplateEngine templateEngine = new TemplateEngine();
    templateEngine.setTemplateResolver(resolver);

    Context context = new Context();
    for(Iterator<String> iterator = vars.keySet().iterator(); iterator.hasNext();){
        String key = iterator.next();
        context.setVariable(key, vars.get(key));
    }

    StringWriter writer = new StringWriter();
    templateEngine.process("example", context, writer);
    return writer.toString();
}
 
Example 4
Source File: WisdomTemplateEngineTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@Test
public void testJavaScript() {
    TemplateEngine engine = createWisdomEngine();
    engine.initialize();
    Context context = new Context();
    context.setVariable("test", "test");

    FakeRouter router = new FakeRouter();
    Controller controller = new FakeController();
    router.addController(controller);

    Assets assets = mock(Assets.class);

    context.setVariable(Routes.ROUTES_VAR, new Routes(router, assets, controller));

    String processed = engine.process("templates/javascript.thl.html", context);
    assertThat(processed).containsIgnoringCase("var t = 'test';");
    assertThat(processed).containsIgnoringCase("var url = '/';");
    assertThat(processed).containsIgnoringCase("$(document).ready(function () {");
}
 
Example 5
Source File: Test.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    // 1.上下文
    Context context = new Context();
    //创建数据模型
    Map<String, Object> dataModel = new HashMap<String, Object>(1);
    dataModel.put("name", "青橙电商系统");
    context.setVariables(dataModel);
    // 2.准备文件
    File dest = new File("d:/test_out.html");
    // 3.生成页面
    try {
        PrintWriter writer = new PrintWriter(dest, "UTF-8");
        //模板解析器
        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
        //模板模型
        resolver.setTemplateMode(TemplateMode.HTML);
        //后缀
        resolver.setSuffix(".html");
        //创建模板引擎
        TemplateEngine engine = new TemplateEngine();
        //设置模板解析器
        engine.setTemplateResolver(resolver);
        //执行模板引擎
        engine.process("test", context, writer);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 6
Source File: ThymeleafTemplateDelegate.java    From reactor-guice with Apache License 2.0 5 votes vote down vote up
@Override
public String template(Object handleObject, ModelMap modelMap, String templateName) {

    String controllerName = handleObject.getClass().getSimpleName();
    String templateDirectory = controllerName.toLowerCase().substring(0, controllerName.length() - "handle".length());
    templateResolver.setPrefix(this.getClass().getResource("/template/" + templateDirectory).getPath() + "/");

    TemplateEngine engine = new TemplateEngine();
    engine.setTemplateResolver(templateResolver);

    Context context = new Context();
    context.setVariables(modelMap);

    return engine.process(templateName, context);
}
 
Example 7
Source File: ThymeleafTest.java    From ext-opensource-netty with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * 使用 Thymeleaf 渲染 HTML
 * @param template  HTML模板
 * @param params 参数
 * @return  渲染后的HTML
 */
public static String render(String template,Map<String,Object> params){
    Context context = new Context();
    context.setVariables(params);
    TemplateEngine engine=new TemplateEngine();
    
    StringTemplateResolver  resolver = new StringTemplateResolver();
    engine.setTemplateResolver(resolver);
    return engine.process(template,context);
}
 
Example 8
Source File: MailUtils.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
* Formate common fix body.
*
* @param silentautoFixTrans the silentauto fix trans
* @param ruleParam the rule param
* @param resourceOwner the resource owner
* @return the string
*/
public static String formateCommonFixBody(List<AutoFixTransaction> silentautoFixTrans,Map<String, String> ruleParam,ResourceOwner resourceOwner) {
    TemplateEngine templateEngine = new TemplateEngine();
    ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
    templateResolver.setTemplateMode("HTML");
    templateResolver.setSuffix(".html");
    templateEngine.setTemplateResolver(templateResolver);
    
    List<String> columnsList = Arrays.asList(CommonUtils.getPropValue(PacmanSdkConstants.PACMAN_MAIL_TEMPLATE_COLUMNS
            + ruleParam.get(PacmanSdkConstants.RULE_ID)).split("\\s*,\\s*"));
   
    Context context = new Context(); 
  
    context.setVariable("columns", columnsList);
    context.setVariable("resources", silentautoFixTrans);
    String policyUrl = getPolicyKnowledgeBasePathURL(ruleParam);
    String name =CommonUtils.getPropValue(PacmanSdkConstants.SEND_EMAIL_SILENT_FIX_ADMIN
            + ruleParam.get(PacmanSdkConstants.RULE_ID));
    
    if(StringUtils.isNullOrEmpty(name)){
  	 name = resourceOwner.getName(); 
    }
    String postFixMessage = CommonUtils.getPropValue(PacmanSdkConstants.EMAIL_FIX_MESSAGE_PREFIX
            + ruleParam.get(PacmanSdkConstants.RULE_ID));
    context.setVariable("AUTOFIX_POST_FIX_MESSAGE", postFixMessage);
    context.setVariable("POLICY_URL", policyUrl);
    context.setVariable("NAME", "Hello "+name);
    context.setVariable("RESOURCE_TYPE", " Resource Type : "+ruleParam.get(PacmanSdkConstants.TARGET_TYPE));
    context.setVariable("AUTO_FIX_APPLIED", "Total AutoFixs Applied : "+silentautoFixTrans.size());
    StringWriter writer = new StringWriter();
    
  if(CommonUtils.getPropValue("pacman.auto.fix.common.email.notifications."
            + ruleParam.get(PacmanSdkConstants.RULE_ID)).equals("commonTemplate")){
    	templateEngine.process("/template/autofix-user-notification-action-common.html", context, writer);
}else{
    	templateEngine.process("/template/autofix-silent-autodelete-usernotification-info.html", context, writer);
    }
    return writer.toString();
    
}
 
Example 9
Source File: SiteGenerator.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Generates site report using thymeleaf template engine.
 *
 * @param diffReport
 *        container with parsed data.
 * @param diffConfiguration
 *        merged configurations from both reports.
 * @param paths
 *        CLI paths.
 * @throws IOException
 *         on failure to write site to disc.
 */
public static void generate(DiffReport diffReport, MergedConfigurationModule diffConfiguration,
        CliPaths paths) throws IOException {
    // setup thymeleaf engine
    final TemplateEngine tplEngine = getTemplateEngine();
    // setup xreference generator
    final XrefGenerator xrefGenerator = new XrefGenerator(paths.getRefFilesPath(),
            paths.getOutputPath().resolve(Main.XREF_FILEPATH), paths.getOutputPath());
    // html generation
    final Path sitepath = paths.getOutputPath().resolve(SITEPATH);
    final FileWriter writer = new FileWriter(sitepath.toString());
    try {
        // write statistics
        generateHeader(tplEngine, writer, diffReport.getStatistics(), diffConfiguration);
        // write parsed content
        generateBody(tplEngine, writer, diffReport, paths, xrefGenerator);
        // write html footer
        tplEngine.process("footer", new Context(), writer);
    }
    finally {
        writer.close();
    }
}
 
Example 10
Source File: SiteGenerator.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Appends to the site a table with parsed data for a single file entry.
 *
 * @param tplEngine
 *        thymeleaf template engine.
 * @param writer
 *        file writer.
 * @param records
 *        checkstyle records for a single file.
 * @param filename
 *        current file name from checkstyle reports.
 * @param anchorCounter
 *        anchor links provider.
 */
private static void generateContent(TemplateEngine tplEngine, FileWriter writer,
        List<CheckstyleRecord> records, String filename,
        AnchorCounter anchorCounter) {
    final Context context = new Context();
    context.setVariable("filename", filename);
    context.setVariable("records", records);
    context.setVariable("anchor", anchorCounter);
    tplEngine.process("content", context, writer);
}
 
Example 11
Source File: PDFThymeleafExample.java    From tutorials with MIT License 5 votes vote down vote up
private String parseThymeleafTemplate() {
    ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode(TemplateMode.HTML);

    TemplateEngine templateEngine = new TemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);

    Context context = new Context();
    context.setVariable("to", "Baeldung.com");

    return templateEngine.process("thymeleaf_template", context);
}
 
Example 12
Source File: PDFThymeleafUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
private String parseThymeleafTemplate() {
    ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode(TemplateMode.HTML);

    TemplateEngine templateEngine = new TemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);

    Context context = new Context();
    context.setVariable("to", "Baeldung.com");

    return templateEngine.process("thymeleaf_template", context);
}
 
Example 13
Source File: WisdomTemplateEngineTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@Test
public void testObjects() {
    FakeContext http = new FakeContext();
    http.session().put("value", "session");
    http.flash().put("value", "flash");
    http.request().data().put("value", "request");
    org.wisdom.api.http.Context.CONTEXT.set(http);

    TemplateEngine engine = createWisdomEngine();
    engine.initialize();
    Context context = new Context();
    context.setVariable("test", "test");

    FakeRouter router = new FakeRouter();
    Controller controller = new FakeController();
    router.addController(controller);

    Assets assets = mock(Assets.class);

    context.setVariable(Routes.ROUTES_VAR, new Routes(router, assets, controller));

    String processed = engine.process("templates/objects.thl.html", context);

    assertThat(processed)
            .contains("<span>session</span>")
            .contains("<span>flash</span>")
            .contains("<span>request</span>");
}
 
Example 14
Source File: SysUserModalController.java    From danyuan-application with Apache License 2.0 4 votes vote down vote up
@RequestMapping(path = "/writeResume", method = RequestMethod.POST)
public BaseResult<String> writeResume(@RequestBody SysUserModal info) throws IllegalArgumentException, IllegalAccessException {
	BaseResult<String> result = new BaseResult<>();
	try {
		// 构造模板引擎
		ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
		resolver.setPrefix("templates/");// 模板所在目录,相对于当前classloader的classpath。
		resolver.setSuffix(".html");// 模板文件后缀
		// resolver.setTemplateMode("HTML5");
		TemplateEngine templateEngine = new TemplateEngine();
		templateEngine.setTemplateResolver(resolver);
		
		// 构造上下文(Model)
		Context context = new Context();
		// 基本
		SysUserBaseInfo base = sysUserBaseService.findById(info.getUserUuid());
		context.setVariable("base", base);
		// 教育
		SysUserEducation education = new SysUserEducation();
		education.setUserUuid(info.getUserUuid());
		List<SysUserEducation> educations = sysUserEducationService.findAll(education);
		context.setVariable("educations", educations);
		// 技能
		SysUserSkill skill = new SysUserSkill();
		skill.setUserUuid(info.getUserUuid());
		List<SysUserSkill> skills = sysUserSkillService.findAll(skill);
		context.setVariable("skills", skills);
		
		// 工作经验
		SysUserWorkExpreience workExpreience = new SysUserWorkExpreience();
		workExpreience.setUserUuid(info.getUserUuid());
		List<SysUserWorkExpreience> workExpreiences = sysUserWorkExpreienceService.findAll(workExpreience);
		context.setVariable("workExpreiences", workExpreiences);
		// 项目经验
		SysUserProject project = new SysUserProject();
		project.setUserUuid(info.getUserUuid());
		List<SysUserProject> projects = sysUserProjectService.findAll(project);
		context.setVariable("projects", projects);
		
		// 评价
		SysUserEvaluate evaluate = new SysUserEvaluate();
		evaluate.setUserUuid(info.getUserUuid());
		evaluate.setType("自我评价");
		evaluate = sysUserEvaluateService.findOne(evaluate);
		context.setVariable("evaluate", evaluate);
		
		// 渲染模板
		String dirString = System.getProperty("user.dir");
		FileWriter write = new FileWriter(dirString + "/file/" + info.getUserUuid() + ".html");
		SysModalInfo sysModalInfo = sysModalInfoService.findOne(new SysModalInfo(info.getModalUuid()));
		
		templateEngine.process("resume/modal/" + sysModalInfo.getModalFilePath(), context, write);
		// 保存简历路径
		base.setResumePath("/file/" + info.getUserUuid() + ".html");
		sysUserBaseService.save(base);
		result.setData("/" + info.getUserUuid() + ".html");
		result.setCode(200);
	} catch (IOException e) {
		System.err.println(e.getMessage());
		result.setCode(-100);
		result.setMsg(e.getMessage());
	}
	return result;
}
 
Example 15
Source File: SiteGenerator.java    From contribution with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Creates beginning part of resulting site.
 *
 * @param tplEngine
 *        thymeleaf template engine.
 * @param writer
 *        file writer.
 * @param statistics
 *        container for statistics.
 * @param diffConfiguration
 *        merged configurations from both reports.
 */
private static void generateHeader(TemplateEngine tplEngine, FileWriter writer,
        Statistics statistics, MergedConfigurationModule diffConfiguration) {
    final Context context = new Context();
    context.setVariable("statistics", statistics);
    context.setVariable("config", diffConfiguration);
    tplEngine.process("header", context, writer);
}