Thymeleaf - 手动处理模板和国际化?

时间:2017-04-27 20:05:04

标签: thymeleaf

我能够手动处理模板(没有Spring Boot),传入变量,然后使用Thymeleaf模板将结果输出到PDF。但是,消息(文本)没有被翻译,似乎没有什么可以接近它。

这是我目前的代码:

    ByteOutputStream os = new ByteOutputStream();
    ITextRenderer renderer = new ITextRenderer();

    Random rand = new Random();
    Integer positiveRandInt = rand.nextInt(Integer.MAX_VALUE) + 1;

    final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
    StandardMessageResolver messageResolver = new StandardMessageResolver();

    messageResolver.getDefaultMessages();

    TenantDTO tenantDTO = operatorService.getOperatorInfo(saleService.getOperatorId(TenantContext.getCurrentTenant()));
    DisplayTransactionDetailsDTO receipt = saleService.getsReceiptForPassenger(transactionNumber);
    ReceiptConfig receiptProperties = operatorService.getOperatorProperty();
    Operator operator = operatorService.getOperatorAddress();

    templateResolver.setPrefix("templates/PDF_Receipt_Template/");
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode("HTML5");
    templateResolver.setCharacterEncoding("UTF-8");

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

    Context ctx = new Context();

    ctx.setVariable("locale", locale);
    ctx.setVariable("lang", "en");

    ctx.setVariable("receipt", receipt);
    ctx.setVariable("receiptItems", receipt.getSalesTransactionItems());
    ctx.setVariable("receiptPayments", receipt.getSalesTransactionPayments());
    ctx.setVariable("receiptPromos", receipt.getSalesTransactionPromos());
    ctx.setVariable("receiptTaxes", receipt.getSalesTransactionTaxSummaries());
    ctx.setVariable("tenant", tenantDTO);
    ctx.setVariable("operator", operator);
    ctx.setVariable("receiptProperties", receiptProperties);

    String htmlContent = templateEngine.process("pdf_template", ctx);

    renderer.setDocumentFromString(htmlContent);
    renderer.layout();
    renderer.createPDF(os);
    renderer.finishPDF();

    byte[] pdfAsBytes = os.getBytes();
    os.close();

    FileOutputStream fos = new FileOutputStream(new File(positiveRandInt.toString() + "_receipt.pdf"));
    fos.write(pdfAsBytes);
    fos.close();

有没有办法在没有Spring的情况下访问Spring Boots消息(Resource Bundle)?通过从TemplateEngine指定位置或资源?然后将加载正确的值,例如:

  • messages.properties
  • messages_en.properties
  • messages_fr.properties

1 个答案:

答案 0 :(得分:0)

MessageSourceResourceBundle.getBundle from org.springframework.context.support

使用指定的基本名称和语言环境以及调用者的类加载器获取资源包。

@param baseName - 资源包的基本名称,完全限定的类名

@param locale - 需要资源包的语言环境

@return给定基本名称和语言环境的资源包

public static final ResourceBundle getBundle(String baseName,
                                             Locale locale)