【问题标题】:Can Thymeleaf do localized template lookups like Freemarker?Thymeleaf 可以像 Freemarker 一样进行本地化模板查找吗?
【发布时间】:2016-07-17 16:19:21
【问题描述】:

加载和包含模板时,Freemarker(默认)uses the locale to build the file names it looks for。例如,使用 en_US 语言环境加载 tos.ftl(模板)会查找:

  1. tos_en_US.ftl
  2. tos_en.ftl
  3. tos.ftl

当页面在不同语言之间完全不同时,这对于翻译整个页面很有用。例如,“服务条款”页面可能大部分是静态的,因此不同的语言会有完全不同的内容。在这种情况下,将整个内容外部化为从消息包加载的消息是一件麻烦事。

我现在正在学习 Thymeleaf,但找不到任何关于类似功能的信息。我知道 Thymeleaf 使用localized message bundles 填充th:text 元素,但它可以加载模板文件的本地化版本吗?

注意:我使用的是 Spring Boot

【问题讨论】:

标签: spring spring-mvc spring-boot freemarker thymeleaf


【解决方案1】:

Thymeleaf 的行为与Spring 4 MVC Internationalization 相同(我猜你在 Spring 中使用 Thymeleaf??),它使用messages.properties 来实现这一点。 例如,您有一个带有#{hello} 消息的模板:

<html xmlns="http://www.w3.org/1999/xhtml" 
  xmlns:th="http://www.thymeleaf.org">
<head>
    <title></title>
</head>
<body>
    <span th:text="#{hello}">
</body>

#{hello} 文本将绑定到messages.properties 属性hello

如果您 locale 将是另一个,例如ru_RU 您只需添加 messages_ru_RU.properties 并更改您的应用程序的 locale

之后,您的消息将从本地化的属性文件中获取。 请注意,如果您使用本地化消息文件,则必须拥有messages.properties 文件。

【讨论】:

  • 感谢您的回答,但它错过了我的意图。我知道消息包,但我想知道实际的模板文件本身是否具有本地化版本。我会澄清这个问题。
【解决方案2】:

我知道这有点太晚了,但这是我尝试使用当前版本的 Thymeleaf 解决这个问题的方法:

假设您在路径(从模板根目录)path/to/template 下有这 2 个本地化模板:

localized_template_en.html
localized_template_ru.html

在你的SomeController.class:

@GetMapping( "/locale_test" )
public String getLocalisedPage( Model model ) {
    return "path/to/template/localized_template_" 
             + LocaleContextHolder.getLocale().getLanguage();
}

因此,如果您使用 Spring 本地化功能(例如 LocaleChangeInterceptor),您将获得正确的模板。如果不是 - 而不是使用 LocaleContextHolder 实现您的自定义逻辑以进行后缀选择。

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 2010-11-20
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    • 2013-09-22
    • 1970-01-01
    相关资源
    最近更新 更多