如何在 ThymeLeaf(非 Web 环境)中为类型注册格式化程序

问题描述 投票:0回答:1

我有一个基于 SpringBoot 的应用程序(SpringBoot 3.2.3)。该应用程序不是 Web 应用程序,即它不使用 servlet、视图等。

在应用程序中,我想创建 HTML 格式的报告并通过电子邮件发送。为了创建 HTML,我想使用 ThymeLeaf。我这样做:

Context context = new Context();

context.setVariable("reportName", reportName);
context.setVariable("someOtherData", data);

return templateEngine.process("report", context);

报告中显示的某些值的类型为

java.time.Duration
,其他值的类型为
java.util.Date
(以及其他一些值)。我的目标是这些值自动格式化为我喜欢的格式。

为此,我创建了 Printer 类并将它们注册到 Spring 注册表中:

@Configuration
public class Config implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addPrinter(new DatePrinter());
        registry.addPrinter(new DurationPrinter());
    }

}

例如,

DatePrinter
看起来像

public class DatePrinter implements Printer<Date> {

    @Override
    public String print(Date date, Locale locale) {
        return new SimpleDateFormat("yyyy-MM-dd").format(date);
    }

}

但注册似乎没有任何效果:在报告中,所有值都通过其

toString
方法显示。

我还尝试将格式化程序注册为

Formatter
而不是
Printer
,但它仍然不起作用。

在我看来,我做了所描述的一切,例如在Thymeleaf 文档中。有人能告诉我如何注册类型的自定义格式化程序吗?

我在这里看到了一些关于这个主题的问题,但它们都是针对 WebMvc 上下文的。

谢谢!

spring spring-boot thymeleaf
1个回答
0
投票

我通过这样做让它工作:

应用程序配置:

public static void spring() {
  SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
  AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext("quickthymeleaftest.formatter");
  resolver.setApplicationContext(app);
  resolver.setPrefix("classpath:/html/");
  resolver.setSuffix(".html");
  resolver.setCharacterEncoding("UTF-8");
  resolver.setTemplateMode(TemplateMode.HTML);
  
  SpringTemplateEngine engine = new SpringTemplateEngine();
  engine.setTemplateResolver(resolver);
  ConversionService c = app.getBean(ConversionService.class);
  
  Context context = new Context();
  final ThymeleafEvaluationContext evaluationContext = new ThymeleafEvaluationContext(app, c);
  context.setVariable(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME, evaluationContext);
  context.setVariable("blah", new Blah());
  
  String html = engine.process("index", context);
  System.out.println(html);
}

在quickthymeleaftest.formatter包中:

@Configuration
public class Config {
    @Bean(name="conversionService")
    public ConversionService getConversionService() {
        ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();
        Set<Converter> converters = new HashSet<>();
        converters.add(new BlahConverter());
        bean.setConverters(converters); //add converters
        bean.afterPropertiesSet();
        return bean.getObject();
    }
}

还有

public class BlahConverter implements Converter<Blah, String> {
    @Override
    public String convert(Blah blah) {
        return "Blah: " + blah.x;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.