Java Code Examples for org.thymeleaf.TemplateEngine

The following are top voted examples for showing how to use org.thymeleaf.TemplateEngine. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openregister-java   File: AssetsBundleCustomErrorHandler.java   View source code 9 votes vote down vote up
public AssetsBundleCustomErrorHandler(Environment environment) {
    this.environment = environment;

    TemplateResolver templateResolver = new TemplateResolver();
    String baseDirForTemplates = System.getProperty("baseDirForTemplates");
    if (baseDirForTemplates != null) {
        templateResolver.setResourceResolver(new FileResourceResolver());
        templateResolver.setPrefix(baseDirForTemplates + "/templates/");
    } else {
        templateResolver.setResourceResolver(new ThymeleafResourceResolver());
        templateResolver.setPrefix("/templates/");
    }
    templateResolver.setTemplateMode("HTML5");
    templateResolver.setCacheable(false);
    templateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
    engine = new TemplateEngine();
    engine.setTemplateResolver(templateResolver);
}
 
Example 2
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: ThymeleafAutoConfigurationTests.java   View source code 7 votes vote down vote up
@Test
public void renderNonWebAppTemplate() throws Exception {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
			ThymeleafAutoConfiguration.class,
			PropertyPlaceholderAutoConfiguration.class);
	assertThat(context.getBeanNamesForType(ViewResolver.class).length).isEqualTo(0);
	try {
		TemplateEngine engine = context.getBean(TemplateEngine.class);
		Context attrs = new Context(Locale.UK,
				Collections.singletonMap("greeting", "Hello World"));
		String result = engine.process("message", attrs);
		assertThat(result).contains("Hello World");
	}
	finally {
		context.close();
	}
}
 
Example 3
Project: xq_seckill_microservice   File: PageGenerator.java   View source code 6 votes vote down vote up
public static void staticPage(GenParam genParam) throws Exception {

        // 构造模板引擎
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(genParam.getResolver());

        // 渲染模板
        Assert.notNull(genParam.getTemplateName(), "templateName must not be null!");
        String filePath = genParam.getOutputPath() + genParam.getTemplateName().split("_")[0] + "/";
        //LOGGER.warn("output file path: {}", filePath);
        File file = new File(filePath);
        if (!file.exists()) file.mkdirs();
        Assert.notNull(genParam.getHouseCode(), "HouseCode must not be null!");
        // 输出文件
        FileWriter write = new FileWriter(filePath + genParam.getHouseCode() + ".shtml");
        templateEngine.process(genParam.getTemplateName(), genParam.getContext(), write);
    }
 
Example 4
Project: javacode-demo   File: ThymeleafDemo.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
    ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
    resolver.setTemplateMode("XHTML");
    resolver.setSuffix(".html");
    TemplateEngine engine = new TemplateEngine();
    engine.setTemplateResolver(resolver);


    Context context = new Context(Locale.FRANCE);
    context.setVariable("date", new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()));
    context.setVariable("contact", new Contact("John", "Doe"));

    List<Contact> contacts = new ArrayList<Contact>();
    contacts.add(new Contact("John","Doe"));
    contacts.add(new Contact("Jane","Doe"));
    context.setVariable("contacts",contacts);

    StringWriter writer = new StringWriter();
    engine.process("org/n3r/sandbox/thymeleaf/home", context, writer);

    System.out.println(writer.toString());
}
 
Example 5
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: ThymeleafAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void createFromConfigClass() throws Exception {
	EnvironmentTestUtils.addEnvironment(this.context, "spring.thymeleaf.mode:XHTML",
			"spring.thymeleaf.suffix:");
	this.context.register(ThymeleafAutoConfiguration.class,
			PropertyPlaceholderAutoConfiguration.class);
	this.context.refresh();
	TemplateEngine engine = this.context.getBean(TemplateEngine.class);
	Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar"));
	String result = engine.process("template.txt", attrs);
	assertThat(result).isEqualTo("<html>bar</html>");
}
 
Example 6
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: ThymeleafAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void overrideCharacterEncoding() throws Exception {
	EnvironmentTestUtils.addEnvironment(this.context,
			"spring.thymeleaf.encoding:UTF-16");
	this.context.register(ThymeleafAutoConfiguration.class,
			PropertyPlaceholderAutoConfiguration.class);
	this.context.refresh();
	this.context.getBean(TemplateEngine.class).initialize();
	ITemplateResolver resolver = this.context.getBean(ITemplateResolver.class);
	assertThat(resolver instanceof TemplateResolver).isTrue();
	assertThat(((TemplateResolver) resolver).getCharacterEncoding())
			.isEqualTo("UTF-16");
	ThymeleafViewResolver views = this.context.getBean(ThymeleafViewResolver.class);
	assertThat(views.getCharacterEncoding()).isEqualTo("UTF-16");
	assertThat(views.getContentType()).isEqualTo("text/html;charset=UTF-16");
}
 
Example 7
Project: adeptj-modules   File: ThymeleafViewEngine.java   View source code 6 votes vote down vote up
@Activate
protected void activate(ComponentContext componentContext) {
    BundleTemplateResolver templateResolver = new BundleTemplateResolver(componentContext.getUsingBundle());
    templateResolver.setPrefix("views/");
    templateResolver.setSuffix(".html");
    templateResolver.setCharacterEncoding("UTF-8");
    templateResolver.setTemplateMode(TemplateMode.HTML);
    // default is cacheable
    templateResolver.setCacheable(false);
    templateResolver.setOrder(1);
    // RK: This is performance intensive OP, need to look into code for a
    // better alternative
    templateResolver.setCheckExistence(true);
    TemplateEngine engine = new TemplateEngine();
    engine.addTemplateResolver(templateResolver);
}
 
Example 8
Project: LsPush-Server   File: CaptchaService.java   View source code 6 votes vote down vote up
@Autowired
public CaptchaService(UserInfoValidator userInfoValidator, LsPushProperties lsPushProperties,
    JavaMailSender mailSender, TemplateEngine templateEngine, ObjectMapper objectMapper,
    UserRepository userRepo) {
    mUserInfoValidator = userInfoValidator;
    serverName = lsPushProperties.getServerName();
    serverUrl = lsPushProperties.getServerUrl();
    serverEmail = lsPushProperties.getServerEmail();
    mMailSender = mailSender;
    mTemplateEngine = templateEngine;
    mObjectMapper = objectMapper;
    mUserRepo = userRepo;
    mAuthCodeMap = CacheBuilder.newBuilder()
        .initialCapacity(100)
        .maximumSize(500)
        .expireAfterWrite(30, TimeUnit.MINUTES)
        .build();

    mStringFunnel = (Funnel<String>) (from, into) -> into.putString(from, StandardCharsets.UTF_8);
    resetBloomFilter();
}
 
Example 9
Project: spring-boot-concourse   File: ThymeleafAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void overrideCharacterEncoding() throws Exception {
	EnvironmentTestUtils.addEnvironment(this.context,
			"spring.thymeleaf.encoding:UTF-16");
	this.context.register(ThymeleafAutoConfiguration.class,
			PropertyPlaceholderAutoConfiguration.class);
	this.context.refresh();
	this.context.getBean(TemplateEngine.class).initialize();
	ITemplateResolver resolver = this.context.getBean(ITemplateResolver.class);
	assertThat(resolver instanceof TemplateResolver).isTrue();
	assertThat(((TemplateResolver) resolver).getCharacterEncoding())
			.isEqualTo("UTF-16");
	ThymeleafViewResolver views = this.context.getBean(ThymeleafViewResolver.class);
	assertThat(views.getCharacterEncoding()).isEqualTo("UTF-16");
	assertThat(views.getContentType()).isEqualTo("text/html;charset=UTF-16");
}
 
Example 10
Project: spring-boot-concourse   File: ThymeleafAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void renderNonWebAppTemplate() throws Exception {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
			ThymeleafAutoConfiguration.class,
			PropertyPlaceholderAutoConfiguration.class);
	assertThat(context.getBeanNamesForType(ViewResolver.class).length).isEqualTo(0);
	try {
		TemplateEngine engine = context.getBean(TemplateEngine.class);
		Context attrs = new Context(Locale.UK,
				Collections.singletonMap("greeting", "Hello World"));
		String result = engine.process("message", attrs);
		assertThat(result).contains("Hello World");
	}
	finally {
		context.close();
	}
}
 
Example 11
Project: thymeleaf-mvc   File: TemplateEngineProducer.java   View source code 6 votes vote down vote up
/**
 * Producer method building and configuring the {@link TemplateEngine} instance to be used in the application. The
 * engine's template resolver is set up to follow MVC requirements. JAX-RS parameter conversion bridges are
 * detected, and if one is present, the engine is set up to use it.
 *
 * Subclasses can override and {@link javax.enterprise.inject.Specializes specialize} this method to add additional
 * configuration (e.g. call {@link TemplateEngine#addDialect(org.thymeleaf.dialect.IDialect)} to add a dialect).
 *
 * @return the newly created and configured {@link TemplateEngine} instance
 */
@Produces public TemplateEngine getTemplateEngine() {
    final TemplateEngine engine = new TemplateEngine();
    final ITemplateResolver tr = new MVCTemplateResolver(servletContext, mvcContext);
    engine.setTemplateResolver(tr);
    try {
        final Class<?> pcbClass = Class.forName("hu.inbuss.thymeleaf.jaxrs.ParamConverterBridge");
        final Bean<?> pcbBean = beanManager.resolve(beanManager.getBeans(pcbClass));
        final CreationalContext pcbContext = beanManager.createCreationalContext(pcbBean);
        final ParamConverterBridge pcb = (ParamConverterBridge) beanManager.getReference(pcbBean, pcbClass, pcbContext);
        pcb.installInto(engine);
    } catch (final ClassNotFoundException cnfe) {
        // the Jersey integration module is not present, do nothing
    }
    return engine;
}
 
Example 12
Project: contestparser   File: ThymeleafAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void renderNonWebAppTemplate() throws Exception {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
			ThymeleafAutoConfiguration.class,
			PropertyPlaceholderAutoConfiguration.class);
	assertEquals(0, context.getBeanNamesForType(ViewResolver.class).length);
	try {
		TemplateEngine engine = context.getBean(TemplateEngine.class);
		Context attrs = new Context(Locale.UK,
				Collections.singletonMap("greeting", "Hello World"));
		String result = engine.process("message", attrs);
		assertThat(result, containsString("Hello World"));
	}
	finally {
		context.close();
	}
}
 
Example 13
Project: validator-sitemap   File: SitemapValidator.java   View source code 6 votes vote down vote up
/**
 * Builds index.html file. This file contains table with links to validation
 * results.
 */
private static void buildIndex() {
	try {
		Collections.sort(results);

		FileWriter writer = new FileWriter(new File("out", "index.html"));

		TemplateEngine templateEngine = new TemplateEngine();
		TemplateResolver templateResolver = new ClassLoaderTemplateResolver();
		templateResolver.setPrefix("resources/");
		templateResolver.setSuffix(".html");
		templateEngine.setTemplateResolver(templateResolver);

		Context ctx = new Context();
		ctx.setVariable("results", results);

		templateEngine.process("index-template", ctx, writer);

		writer.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 14
Project: java-docs-samples   File: GaeInfoServlet.java   View source code 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 15
Project: java-docs-samples   File: GaeInfoServlet.java   View source code 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 16
Project: java-docs-samples   File: MetadataServlet.java   View source code 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 17
Project: contribution   File: TemplateProcessor.java   View source code 6 votes vote down vote up
/**
 * Generates output file with release notes using Thymeleaf.
 * @param variables the map which represents template variables.
 * @param outputFile output file.
 * @param templateFilename template name.
 * @throws IOException if I/O error occurs.
 */
public static void generateWithThymeleaf(Map<String, Object> variables, String outputFile,
        String templateFilename) throws IOException {

    final TemplateEngine engine = new TemplateEngine();
    final AbstractConfigurableTemplateResolver resolver = new ClassLoaderTemplateResolver();
    resolver.setPrefix(TEMPLATE_FOLDER_PATH);
    engine.setTemplateResolver(resolver);

    final IContext ctx = new Context(Locale.US, variables);

    try (Writer fileWriter = new OutputStreamWriter(
            new FileOutputStream(outputFile), StandardCharsets.UTF_8)) {
        engine.process(templateFilename, ctx, fileWriter);
    }
}
 
Example 18
Project: contribution   File: SiteGenerator.java   View source code 6 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 19
Project: bench4j   File: HtmlIndexPage.java   View source code 6 votes vote down vote up
/**
 * Generates the index page.
 *
 * @param _records
 *            the list of records.
 * @throws IOException
 */
public void generate(Map<RecordKey, BenchRecord> _records) throws IOException {
	final TemplateEngine templateEngine = new TemplateEngine();
	final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();

	// XHTML is the default mode, but we set it anyway for better
	// understanding of code
	templateResolver.setTemplateMode("HTML5");
	templateResolver.setCacheable(true);
	templateResolver.setPrefix("templates/");
	templateResolver.setSuffix(".html");
	templateEngine.setTemplateResolver(templateResolver);
	try (final FileWriter fw = new FileWriter(new File(reportFolder, "index.html"))) {
		templateEngine.process("index", new BenchContext(_records), fw);
	}
}
 
Example 20
Project: thymeleaf-extras-sqldialect   File: StandaloneThymeleafServlet.java   View source code 6 votes vote down vote up
/**
 * Initialize the Thymeleaf template engine.
 */
@Override
public void init() {
	ServletConfig config = this.getServletConfig();

	ServletContextTemplateResolver templateresolver = new ServletContextTemplateResolver();
	templateresolver.setPrefix(config.getInitParameter(INIT_PARAM_PREFIX));
	templateresolver.setSuffix(config.getInitParameter(INIT_PARAM_SUFFIX));
	templateresolver.setTemplateMode(config.getInitParameter(INIT_PARAM_TEMPLATEMODE));
	templateresolver.setCacheable(false);
	templateresolver.setCharacterEncoding(CHARACTER_ENCODING);

	templateengine = new TemplateEngine();
	templateengine.setTemplateResolver(templateresolver);
       Set<IDialect> dialects = new HashSet<IDialect>();
	dialects.add(new SpringStandardDialect());
	dialects.add(new SqlDialect());
       templateengine.setDialects(dialects);
       templateengine.initialize();
}
 
Example 21
Project: Brisk   File: ThymeleafTemplateRenderer.java   View source code 6 votes vote down vote up
@Override
public String render(TemplateContext context)
        throws Exception
{
    TemplateEngine templateEngine = getTemplateEngine(context);

    Map<String, Object> variables = new HashMap<>(3);
    variables.put("site", context.site);
    variables.put("page", context.page);
    variables.put("contents", context.contents);

    SiteContext thymeleafContext = new SiteContext();
    thymeleafContext.setSiteKey(context.site.key);

    thymeleafContext.setVariables(variables);

    return templateEngine.process(context.page.getMasterTemplate(), thymeleafContext);
}
 
Example 22
Project: solr-thymeleaf   File: ThymeleafResponseWriter.java   View source code 6 votes vote down vote up
protected TemplateEngine getEngine() {
   // create engine
   if (templateEngine == null) {
      // use solr core here
      templateResolver.setPrefix(configuration.get("tl.prefix", "templates/"));

      TemplateEngine te = new TemplateEngine();
      te.setTemplateResolver(templateResolver);
      te.addDialect(layoutDialect);

      // check race condition, avoid synchronized block
      if (templateEngine == null) {
         templateEngine = te;
      }
   }

   return templateEngine;
}
 
Example 23
Project: bench4j   File: HtmlIndexPage.java   View source code 6 votes vote down vote up
/**
 * Generates the index page.
 *
 * @param _records
 *            the list of records.
 * @throws IOException
 */
public void generate(Map<RecordKey, BenchRecord> _records) throws IOException {
	final TemplateEngine templateEngine = new TemplateEngine();
	final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();

	// XHTML is the default mode, but we set it anyway for better
	// understanding of code
	templateResolver.setTemplateMode("HTML5");
	templateResolver.setCacheable(true);
	templateResolver.setPrefix("templates/");
	templateResolver.setSuffix(".html");
	templateEngine.setTemplateResolver(templateResolver);
	try (final FileWriter fw = new FileWriter(new File(reportFolder, "index.html"))) {
		templateEngine.process("index", new BenchContext(_records), fw);
	}
}
 
Example 24
Project: jooby   File: Thl.java   View source code 6 votes vote down vote up
@Override
public void configure(final Env env, final Config conf, final Binder binder) throws Throwable {
  ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
  boolean cacheable = !env.name().equals("dev");
  /** Defaults: */
  resolver.setCacheable(cacheable);
  resolver.setPrefix(prefix);
  resolver.setSuffix(suffix);
  resolver.setTemplateMode(TemplateMode.HTML);

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

  if (callback != null) {
    callback.accept(engine, conf);
  }

  binder.bind(TemplateEngine.class).toInstance(engine);
  binder.bind(ITemplateEngine.class).toInstance(engine);

  Multibinder.newSetBinder(binder, Renderer.class)
      .addBinding()
      .toInstance(new ThlEngine(engine, env));
}
 
Example 25
Project: stdlib   File: GuiceCoreTemplater.java   View source code 6 votes vote down vote up
/**
 * Retrieve or build a Thymeleaf templater
 *
 * @return
 */
private ThymeleafTemplater getOrCreateTemplater()
{
	ThymeleafTemplater templater = this.templater.get();

	// Lazy-create a ThymeleafTemplater
	if (templater == null)
	{
		final TemplateEngine engine = getOrCreateEngine();

		templater = new ThymeleafTemplater(engine, configuration, metrics, userProvider);

		templater.set("coreRestPrefix", coreRestPrefix);
		templater.set("coreRestEndpoint", coreRestEndpoint.toString());
		templater.set("coreServices", services);
		templater.set("currentUser", new ThymeleafCurrentUserUtils(userProvider));

		this.templater = new WeakReference<>(templater);
	}

	return templater;
}
 
Example 26
Project: stdlib   File: ThymeleafTemplater.java   View source code 6 votes vote down vote up
@Inject
public ThymeleafTemplater(final TemplateEngine engine,
                          final GuiceConfig configuration,
                          MetricRegistry metrics,
                          Provider<CurrentUser> userProvider)
{
	if (engine.getTemplateResolvers().isEmpty())
	{
		throw new IllegalArgumentException("No Template Resolvers have been configured for thymeleaf (missing import?)");
	}

	this.engine = engine;
	this.configuration = configuration;

	this.calls = metrics.timer(GuiceMetricNames.THYMELEAF_CALL_TIMER);
	this.failures = metrics.meter(GuiceMetricNames.THYMELEAF_RENDER_EXCEPTION_METER);

	data.put("currentUser", new ThymeleafCurrentUserUtils(userProvider));
}
 
Example 27
Project: wisdom   File: WisdomTemplateEngineTest.java   View source code 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 28
Project: jbake-rtl-jalaali   File: ThymeleafTemplateEngine.java   View source code 5 votes vote down vote up
private void initializeTemplateEngine(String mode) {
	if (mode.equals(templateMode)) {
		return;
	}
    templateMode = mode;
    templateResolver = new FileTemplateResolver();
    templateResolver.setPrefix(templatesPath.getAbsolutePath() + File.separatorChar);
    templateResolver.setCharacterEncoding(config.getString(Keys.TEMPLATE_ENCODING));
    templateResolver.setTemplateMode(mode);
    templateEngine = new TemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);
}
 
Example 29
Project: okmail   File: OkMailClientTest.java   View source code 5 votes vote down vote up
@Test
@Ignore
public void testThymeleafTemplate() throws IOException, MessagingException {

    ClassLoaderTemplateResolver templateResolver =
            new ClassLoaderTemplateResolver();

    templateResolver.setTemplateMode(TemplateMode.HTML);
    templateResolver.setPrefix("/templates/");
    templateResolver.setSuffix(".html");
    templateResolver.setCacheTTLMs(Long.valueOf(3600000L));

    templateResolver.setCharacterEncoding("UTF-8");
    templateResolver.setCacheable(true);

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

    Context ctx = new Context();
    ctx.setLocale(Locale.ENGLISH);
    ctx.setVariable("username", "ricky");
    ctx.setVariable("url", "http://www.thymeleaf.org");
    ctx.setVariable("email", "[email protected]");

    StringWriter sw = new StringWriter(1024);
    templateEngine.process("registry", ctx, sw);

    String output = sw.toString();
    System.out.println(output);

    Mail mail = Mail.newBuilder().from(from,"ricky fung")
            .to(to)
            .subject("测试邮件[模板邮件-Thymeleaf]")
            .html(output)
            .build();

    client.send(mail);
}
 
Example 30
Project: okmail   File: ThymeleafTest.java   View source code 5 votes vote down vote up
@Test
@Ignore
public void testApp() throws IOException {

    //use thymeleaf
    ClassLoaderTemplateResolver templateResolver =
            new ClassLoaderTemplateResolver();

    templateResolver.setTemplateMode(TemplateMode.HTML);
    templateResolver.setPrefix("/templates/");
    templateResolver.setSuffix(".html");
    templateResolver.setCacheTTLMs(Long.valueOf(3600000L));

    templateResolver.setCharacterEncoding("UTF-8");
    templateResolver.setCacheable(true);

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

    Context ctx = new Context();
    ctx.setLocale(Locale.ENGLISH);
    ctx.setVariable("username", "ricky");
    ctx.setVariable("url", "http://www.thymeleaf.org");
    ctx.setVariable("email", "[email protected]");

    StringWriter sw = new StringWriter(1024);
    templateEngine.process("registry", ctx, sw);

    String output = sw.toString();
    System.out.println(output);
}
 
Example 31
Project: ToDoApp-Spring   File: ThymeleafConfig.java   View source code 5 votes vote down vote up
@Bean
public TemplateEngine templateEngine() {
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.setEnableSpringELCompiler(true);
    engine.setTemplateResolver(templateResolver());
    return engine;
}
 
Example 32
Project: spring-rest-skeleton   File: EmailConfiguration.java   View source code 5 votes vote down vote up
@Bean
public TemplateEngine emailTemplateEngine() {
	final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
	templateEngine.addTemplateResolver(htmlTemplateResolver());
	templateEngine.setTemplateEngineMessageSource(messageSource);
	return templateEngine;
}
 
Example 33
Project: custom-gradle-plugin-portal   File: ResourceConfig.java   View source code 5 votes vote down vote up
@Bean
public TemplateEngine templateEngine() {
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.setEnableSpringELCompiler(true);
    engine.setTemplateResolver(templateResolver());
    return engine;
}
 
Example 34
Project: java-demo   File: WebConfig.java   View source code 5 votes vote down vote up
@Bean
public TemplateEngine templateEngine() {
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.setEnableSpringELCompiler(true);
    engine.setTemplateResolver(templateResolver());
    return engine;
}
 
Example 35
Project: lodsve-framework   File: ThymeleafTemplateResource.java   View source code 5 votes vote down vote up
@Override
public String renderTemplate() {
    TemplateEngine templateEngine = new TemplateEngine();
    AbstractConfigurableTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
    templateResolver.setTemplateMode(this.templateMode);

    templateEngine.setTemplateResolver(templateResolver);

    return templateEngine.process(template, new Context(Locale.SIMPLIFIED_CHINESE, context));
}
 
Example 36
Project: jlineup   File: HTMLReportWriter.java   View source code 5 votes vote down vote up
String renderReport(String template, List<ScreenshotComparisonResult> screenshotComparisonResults) throws FileNotFoundException {

        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        templateResolver.setTemplateMode("HTML");
        templateResolver.setPrefix("templates/");
        templateResolver.setSuffix(".html");
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);

        final Map<String, Object> variables = prepareVariablesForReportTemplate(screenshotComparisonResults);

        return templateEngine.process(template, new Context(Locale.US, variables));
    }
 
Example 37
Project: thymeleaf3-shiro   File: ShiroDialectTest.java   View source code 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
	//Set up shiro
	Ini ini = new Ini();
	Ini.Section usersSection = ini.addSection("users");
	usersSection.put(USER1, PASS1 + ",rolea,roled");
	usersSection.put(USER2, PASS2 + ",roleb,rolec");
	usersSection.put(USER3, PASS3 + ",rolec,rolee");
	Ini.Section rolesSection = ini.addSection("roles");
	rolesSection.put("rolea", "*");
	rolesSection.put("roleb", "permtype1:permaction1:perminst1");
	rolesSection.put("rolec", "permtype1:permaction2:*");
	rolesSection.put("roled", "permtype3:*");
	Factory<SecurityManager> factory = new TestIniSecurityManagerFactory(ini);
	SecurityManager secMgr = factory.getInstance();
	setSecurityManager(secMgr);

	//Set up thymeleaf
	ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
	templateResolver.setCacheable(false);
	templateResolver.setCharacterEncoding("UTF-8");
	templateResolver.setTemplateMode("HTML5");

	templateEngine = new TemplateEngine();
	templateEngine.setTemplateResolver(templateResolver);
	templateEngine.addDialect("shiro", new ShiroDialect());
}
 
Example 38
Project: graviteeio-access-management   File: ThymeleafConfiguration.java   View source code 5 votes vote down vote up
@Bean
public TemplateEngine getTemplateEngine(ITemplateResolver templateResolver) {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setEnableSpringELCompiler(true);
    templateEngine.setTemplateResolver(templateResolver);
    return templateEngine;
}
 
Example 39
Project: graviteeio-access-management   File: ThymeleafConfiguration.java   View source code 5 votes vote down vote up
@Bean
public ViewResolver getViewResolver(TemplateEngine templateEngine) {
    ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
    viewResolver.setTemplateEngine(templateEngine);
    viewResolver.setCharacterEncoding("UTF-8");
    return viewResolver;
}
 
Example 40
Project: spring-rest-skeleton   File: EmailConfiguration.java   View source code 5 votes vote down vote up
@Bean
public TemplateEngine emailTemplateEngine() {
	final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
	templateEngine.addTemplateResolver(htmlTemplateResolver());
	templateEngine.setTemplateEngineMessageSource(messageSource);
	return templateEngine;
}