org.thymeleaf.TemplateEngine Java Examples

The following examples show how to use org.thymeleaf.TemplateEngine. 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: 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 #2
Source File: GaeInfoServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void init() {
  // Setup ThymeLeaf
  ServletContextTemplateResolver templateResolver =
      new ServletContextTemplateResolver(this.getServletContext());

  templateResolver.setPrefix("/WEB-INF/templates/");
  templateResolver.setSuffix(".html");
  templateResolver.setCacheTTLMs(Long.valueOf(1200000L)); // TTL=20m

  // Cache is set to true by default. Set to false if you want templates to
  // be automatically updated when modified.
  templateResolver.setCacheable(true);

  templateEngine = new TemplateEngine();
  templateEngine.setTemplateResolver(templateResolver);
}
 
Example #3
Source File: SwaggerMappingSupport.java    From swagger with Apache License 2.0 6 votes vote down vote up
public SwaggerMappingSupport(ServletContext servletContext, String urlPatternMapping) throws ServletException {
    this.contextPath = servletContext.getContextPath();
    urlPrefix = contextPath + urlPatternMapping;
    urlPrefix = urlPrefix.replaceAll("/{2,}", "/");
    if (!"/".equals(urlPrefix) && urlPrefix.endsWith("/")) {
        urlPrefix = urlPrefix.substring(0, urlPrefix.length() - 1);
    }
    requestMatchers = Arrays.stream(RESOURCE_PATTERNS)
            .map(pattern -> String.join("/", this.contextPath, urlPatternMapping, pattern))
            .map(pattern -> pattern.replaceAll("/{2,}", "/"))
            .map(pattern -> new AntPathRequestMatcher(pattern, HttpMethod.GET.name()))
            .collect(Collectors.toList());

    ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(SwaggerFilter.class.getClassLoader());
    templateResolver.setPrefix(TEMPLATES_PATH + "/");
    templateResolver.setTemplateMode(TemplateMode.HTML);
    TemplateEngine templateEngine = new TemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);
    this.templateEngine = templateEngine;
}
 
Example #4
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 #5
Source File: GaeInfoServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void init() {
  // Setup ThymeLeaf
  ServletContextTemplateResolver templateResolver =
      new ServletContextTemplateResolver(this.getServletContext());

  templateResolver.setPrefix("/WEB-INF/templates/");
  templateResolver.setSuffix(".html");
  templateResolver.setCacheTTLMs(1200000L); // TTL=20m

  // Cache is set to true by default. Set to false if you want templates to
  // be automatically updated when modified.
  templateResolver.setCacheable(true);

  templateEngine = new TemplateEngine();
  templateEngine.setTemplateResolver(templateResolver);
}
 
Example #6
Source File: OghamSpringBoot1AutoConfigurationTests.java    From ogham with Apache License 2.0 6 votes vote down vote up
@Test
public void oghamInWebContext() throws Exception {
	context.register(WebMvcAutoConfiguration.class, OghamSpringBoot1AutoConfiguration.class);
	context.refresh();
	MessagingService messagingService = context.getBean(MessagingService.class);
	checkEmail(messagingService);
	checkSms(messagingService);
	OghamInternalAssertions.assertThat(messagingService)
		.sendGrid()
			.apiKey(equalTo("ogham"))
			.client(allOf(isA(SendGrid.class), not(isSpringBeanInstance(context, SendGrid.class))))
			.and()
		.thymeleaf()
			.all()
				.engine(isA(TemplateEngine.class))
				.and()
			.and()
		.freemarker()
			.all()
				.configuration()
					.defaultEncoding(equalTo(StandardCharsets.US_ASCII.name()));
}
 
Example #7
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 #8
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 #9
Source File: OghamSpringBoot1AutoConfigurationTests.java    From ogham with Apache License 2.0 6 votes vote down vote up
@Test
public void oghamAlone() throws Exception {
	context.register(OghamSpringBoot1AutoConfiguration.class);
	context.refresh();
	MessagingService messagingService = context.getBean(MessagingService.class);
	checkEmail(messagingService);
	checkSms(messagingService);
	OghamInternalAssertions.assertThat(messagingService)
		.sendGrid()
			.apiKey(equalTo("ogham"))
			.client(allOf(isA(SendGrid.class), not(isSpringBeanInstance(context, SendGrid.class))))
			.and()
		.thymeleaf()
			.all()
				.engine(isA(TemplateEngine.class))
				.and()
			.and()
		.freemarker()
			.all()
				.configuration()
					.defaultEncoding(equalTo(StandardCharsets.US_ASCII.name()));
}
 
Example #10
Source File: ThymeleafTest.java    From ext-opensource-netty with Mozilla Public License 2.0 6 votes vote down vote up
public static void testB() {
	 ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
     //模板所在目录,相对于当前classloader的classpath。
     resolver.setPrefix("static/");
    
     ///模板文件后缀
     // resolver.setSuffix(".html");
     // resolver.setCacheable(false);//设置不缓存
     // resolver.setTemplateMode("HTML5");
     
     TemplateEngine engine = new TemplateEngine();
     engine.setTemplateResolver(resolver);
     Context context = new Context();
     context.setVariable("socketurl", "ws");
     System.out.println(engine.process("websocket.html", context)); 
}
 
Example #11
Source File: OghamSpringBoot2AutoConfigurationTests.java    From ogham with Apache License 2.0 6 votes vote down vote up
@Test
public void oghamInWebContext() throws Exception {
	contextRunner = contextRunner.withConfiguration(of(WebMvcAutoConfiguration.class, OghamSpringBoot2AutoConfiguration.class));
	contextRunner.run((context) -> {
		MessagingService messagingService = context.getBean(MessagingService.class);
		checkEmail(messagingService);
		checkSms(messagingService);
		OghamInternalAssertions.assertThat(messagingService)
			.sendGrid()
				.apiKey(equalTo("ogham"))
				.client(allOf(isA(SendGrid.class), not(isSpringBeanInstance(context, SendGrid.class))))
				.and()
			.thymeleaf()
				.all()
					.engine(isA(TemplateEngine.class))
					.and()
				.and()
			.freemarker()
				.all()
					.configuration()
						.defaultEncoding(equalTo(StandardCharsets.US_ASCII.name()));
	});
}
 
Example #12
Source File: MetadataServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void init() {
  // Setup ThymeLeaf
  ServletContextTemplateResolver templateResolver =
      new ServletContextTemplateResolver(this.getServletContext());

  templateResolver.setPrefix("/WEB-INF/templates/");
  templateResolver.setSuffix(".html");
  templateResolver.setCacheTTLMs(Long.valueOf(1200000L)); // TTL=20m

  // Cache is set to true by default. Set to false if you want templates to
  // be automatically updated when modified.
  templateResolver.setCacheable(true);

  templateEngine = new TemplateEngine();
  templateEngine.setTemplateResolver(templateResolver);
}
 
Example #13
Source File: MyFileResourceResolver.java    From wisdom with Apache License 2.0 5 votes vote down vote up
public InputStream getResourceAsStream(final TemplateProcessingParameters templateProcessingParameters, String resourceName) {
    Validate.notNull(resourceName, "Resource name cannot be null");
    System.out.println(resourceName);

    if (resourceName.startsWith("file:")) {
        resourceName = resourceName.substring(5);
    }

    final File resourceFile = new File(resourceName);
    try {
        return new FileInputStream(resourceFile);
    } catch (final Exception e) {
        if (logger.isDebugEnabled()) {
            if (logger.isTraceEnabled()) {
                logger.trace(
                        String.format(
                                "[THYMELEAF][%s][%s] Resource \"%s\" could not be resolved. This can be normal as " +
                                        "maybe this resource is not intended to be resolved by this resolver. " +
                                        "Exception is provided for tracing purposes: ",
                                TemplateEngine.threadIndex(), templateProcessingParameters.getTemplateName(),
                                resourceName),
                        e);
            } else {
                logger.debug(
                        String.format(
                                "[THYMELEAF][%s][%s] Resource \"%s\" could not be resolved. This can be normal as " +
                                        "maybe this resource is not intended to be resolved by this resolver. " +
                                        "Exception message is provided: %s: %s",
                                TemplateEngine.threadIndex(), templateProcessingParameters.getTemplateName(),
                                resourceName, e.getClass().getName(), e.getMessage()));
            }
        }
        return null;
    }
}
 
Example #14
Source File: ThymeleafViewResultHandler.java    From oxygen with Apache License 2.0 5 votes vote down vote up
ThymeleafResolver() {
  this.templateEngine = new TemplateEngine();
  ResourceTemplateResolver templateResolver = new ResourceTemplateResolver(
      WebConfigKeys.VIEW_PREFIX_THYMELEAF.getValue());
  templateResolver.setCacheable(WebConfigKeys.VIEW_CACHE.castValue(boolean.class));
  this.templateEngine.setTemplateResolver(templateResolver);
}
 
Example #15
Source File: HTMLReportWriter.java    From jlineup with Apache License 2.0 5 votes vote down vote up
public HTMLReportWriter(FileService fileService) {
    this.fileService = fileService;

    templateResolver.setTemplateMode("HTML");
    templateResolver.setPrefix("templates/");
    templateResolver.setSuffix(".html");
    templateEngine = new TemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);
}
 
Example #16
Source File: ThymeleafConfiguration.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Bean
public ThymeleafTemplateEngine getTemplateEngine() {
    ThymeleafTemplateEngine thymeleafTemplateEngine = ThymeleafTemplateEngine.create(vertx);
    TemplateEngine templateEngine = thymeleafTemplateEngine.getDelegate().getThymeleafTemplateEngine();

    // set template resolvers
    DomainBasedTemplateResolver overrideTemplateResolver = (DomainBasedTemplateResolver) overrideTemplateResolver();
    overrideTemplateResolver.setTemplateEngine(templateEngine);
    templateEngine.setTemplateResolver(overrideTemplateResolver);
    templateEngine.addTemplateResolver(defaultTemplateResolver());

    return thymeleafTemplateEngine;
}
 
Example #17
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 #18
Source File: ThymeleafParserAssertions.java    From ogham with Apache License 2.0 5 votes vote down vote up
private static TemplateEngine getEngine(ThymeleafParser parser) {
	try {
		return (TemplateEngine) FieldUtils.readField(parser, "engine", true);
	} catch (IllegalAccessException e) {
		throw new IllegalStateException("Failed to get 'engine' field of ThymeleafParser", e);
	}
}
 
Example #19
Source File: ThymeleafViewEngine.java    From generator-jvm with MIT License 5 votes vote down vote up
@PostConstruct
public void postConstruct() {
  final ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(servletContext);
  resolver.setPrefix("/WEB-INF/layouts/");
  resolver.setSuffix(".html");
  resolver.setTemplateMode(TemplateMode.HTML);
  resolver.setCacheable(false);
  engine = new TemplateEngine();
  engine.setTemplateResolver(resolver);
}
 
Example #20
Source File: DefaultTemplateEngineProducer.java    From ozark with Apache License 2.0 5 votes vote down vote up
@Produces
@ViewEngineConfig
public TemplateEngine getTemplateEngine() {

    ITemplateResolver resolver = new ServletContextTemplateResolver(this.servletContext);

    TemplateEngine engine = new TemplateEngine();
    engine.setTemplateResolver(resolver);
    return engine;

}
 
Example #21
Source File: TemplatingEngine.java    From EDDI with Apache License 2.0 5 votes vote down vote up
private TemplateEngine getTemplateEngine(TemplateMode templateMode) {
    if (templateMode.equals(TemplateMode.HTML)) {
        return htmlTemplateEngine.getTemplateEngine();
    } else {
        return textTemplateEngine.getTemplateEngine();
    }
}
 
Example #22
Source File: TemplateEngineModule.java    From EDDI with Apache License 2.0 5 votes vote down vote up
private TemplateEngine createTemplateEngine(TemplateMode templateMode) {
    TemplateEngine templateEngine = new TemplateEngine();
    StringTemplateResolver templateResolver = new StringTemplateResolver();
    templateResolver.setTemplateMode(templateMode);
    templateEngine.addTemplateResolver(templateResolver);

    return templateEngine;
}
 
Example #23
Source File: ThymeleafTemplateProcessorImpl.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@Inject
public ThymeleafTemplateProcessorImpl() {
  final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
  templateResolver.setTemplateMode(HTML);
  templateResolver.setSuffix(".html");
  templateResolver.setCacheTTLMs(3600000L);
  this.templateEngine = new TemplateEngine();
  this.templateEngine.setTemplateResolver(templateResolver);
}
 
Example #24
Source File: ThymeleafV2EngineConfigBuilder.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Override
protected void configureMessageResolvers(TemplateEngine engine) {
	super.configureMessageResolvers(engine);
	if (defaultMessageResolvers != null) {
		engine.setDefaultMessageResolvers(defaultMessageResolvers);
	}
}
 
Example #25
Source File: ThymeleafV2EngineConfigBuilder.java    From ogham with Apache License 2.0 5 votes vote down vote up
private void configureTemplateModeHandlers(TemplateEngine engine) {
	if (defaultTemplateModeHandlers != null) {
		engine.setDefaultTemplateModeHandlers(defaultTemplateModeHandlers);
	}
	if (templateModeHandlers != null) {
		engine.setTemplateModeHandlers(templateModeHandlers);
	}
}
 
Example #26
Source File: AbstractThymeleafEngineConfigBuilder.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Override
public TemplateEngine build() {
	TemplateEngine engine = buildContext.register(new TemplateEngine());
	configureDialects(engine);
	configureMessageResolvers(engine);
	configureTemplateResolvers(engine);
	configureCacheManager(engine);
	return engine;
}
 
Example #27
Source File: AbstractThymeleafEngineConfigBuilder.java    From ogham with Apache License 2.0 5 votes vote down vote up
protected void configureDialects(TemplateEngine engine) {
	if (dialects != null) {
		engine.setDialects(dialects);
	}
	if (dialectsByPrefix != null) {
		engine.setDialectsByPrefix(dialectsByPrefix);
	}
}
 
Example #28
Source File: AbstractThymeleafBuilder.java    From ogham with Apache License 2.0 5 votes vote down vote up
protected TemplateEngine buildEngine() {
	TemplateEngine builtEngine;
	if (engine != null) {
		LOG.debug("Using custom Thymeleaf engine");
		builtEngine = engine;
	} else if (engineBuilder != null) {
		LOG.debug("Using custom Thymeleaf engine built using engine()");
		builtEngine = engineBuilder.build();
	} else {
		LOG.debug("Using default Thymeleaf engine");
		builtEngine = buildContext.register(new TemplateEngine());
	}
	builtEngine.addTemplateResolver(buildTemplateResolver(builtEngine));
	return builtEngine;
}
 
Example #29
Source File: TemplateEngineSupplierProducer.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
@Bean
@Scope(proxyMode = ScopedProxyMode.INTERFACES)
public TemplateEngineSupplier getTemplateEngineSupplier(PortletConfig portletConfig, ServletContext servletContext,
	BeanFactory beanFactory) {
	TemplateEngine templateEngine = new TemplateEngine();
	templateEngine.setMessageResolver(new PortletMessageResolver(portletConfig));
	templateEngine.setTemplateResolver(new PortletTemplateResolver(servletContext,
			new SpringConfigurationSupplier(beanFactory)));

	return new DefaultTemplateEngineSupplier(templateEngine);
}
 
Example #30
Source File: ShiroDialectTest.java    From thymeleaf-extras-shiro with Apache License 2.0 5 votes vote down vote up
private static void setupThymeleaf() {
    ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
    templateResolver.setCacheable(false);
    templateResolver.setCharacterEncoding("UTF-8");
    templateResolver.setTemplateMode(TemplateMode.HTML);

    templateEngine = new TemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);
    templateEngine.addDialect("shiro", new ShiroDialect());

}