Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions grails-doc/src/en/guide/i18n/changingLocales.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,28 @@ By default, the user locale is detected from the incoming `Accept-Language` head

Grails will automatically switch the user's locale and subsequent requests will use the switched locale.

To offer a language selector, the i18n plugin discovers the locales your application is actually translated into by scanning the classpath for `messages_&#42;.properties` bundles (plus the default locale, configurable via `grails.i18n.default.locale`). This list is exposed as the `AvailableLocaleResolver` bean and published to the servlet context under the `availableLocales` attribute. The `<g:localeSelect available="true"/>` tag renders a `<select>` limited to those locales, and you can iterate the list directly in a view to build your own switcher:
Comment thread
codeconsole marked this conversation as resolved.

[source,xml]
----
<g:each in="${application.getAttribute('availableLocales')}" var="locale">
<a href="?lang=${locale.toLanguageTag()}">${locale.getDisplayName(locale)}</a>
</g:each>
----

By default every `&#42;.properties` bundle on the classpath is considered, so locales contributed by plugins &mdash; whose bundles are namespaced (for example `spring-security-core_fr.properties`) &mdash; are listed alongside your application's own. Candidate suffixes are validated against the ISO language codes (and the ISO country codes when a country is present), so non-i18n properties files (such as `application.properties`) are ignored. To restrict discovery to your application's own `messages_&#42;.properties` bundles, set `grails.i18n.availableLocales.includePlugins=false`:

[source,yaml]
.grails-app/conf/application.yml
----
grails:
i18n:
availableLocales:
includePlugins: false # list only the application's own translations
----

Applications created with `grails create-app` include a ready-made language dropdown in the default layout that uses exactly this mechanism.

By default, Grails uses {springapi}org/springframework/web/servlet/i18n/SessionLocaleResolver.html[SessionLocaleResolver] as the `localeResolver` bean.

You can select a different resolver strategy with the `grails.i18n.localeResolver` configuration property, without declaring a bean:
Expand Down
4 changes: 4 additions & 0 deletions grails-doc/src/en/ref/Tags - GSP/localeSelect.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ Generates an HTML select with ``Locale``s as values
----
<!-- create a locale select -->
<g:localeSelect name="myLocale" value="${locale}" />

<!-- list only the locales the application is translated into -->
<g:localeSelect name="myLocale" available="true" />
----


Expand All @@ -46,5 +49,6 @@ Attributes
* `name` - The name to be used for the select box
* `value` (optional) - The selected {javase}java.base/java/util/Locale.html[Locale]; defaults to the current request locale if not specified
* `locale` (optional) - The {javase}java.base/java/util/Locale.html[Locale] to use for formatting the locale names. Defaults to the current request locale and then the system default locale if not specified
* `available` (optional) - If `true`, lists only the locales the application is actually translated into (those with a `messages_&#42;.properties` bundle on the classpath, as discovered by the i18n plugin) rather than every locale the JVM knows about. Defaults to `false`.


16 changes: 16 additions & 0 deletions grails-forge/grails-forge-core/src/main/resources/gsp/main.gsp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,22 @@
<asset:image class="w-75" src="grails.svg" alt="Grails Logo"/>
</a>
<ul class="navbar-nav ms-auto">
<g:set var="availableLocales" value="${application.getAttribute('availableLocales')}"/>
<g:if test="${availableLocales && availableLocales.size() > 1}">
<g:set var="currentLocale" value="${org.springframework.web.servlet.support.RequestContextUtils.getLocale(request)}"/>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="localeDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
<i class="bi bi-globe me-1"></i>${currentLocale.getDisplayName(currentLocale)}
</a>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="localeDropdown">
<g:each in="${availableLocales}" var="availableLocale">
<li>
<a class="dropdown-item${availableLocale.language == currentLocale.language ? ' active' : ''}" href="?lang=${availableLocale.toLanguageTag()}">${availableLocale.getDisplayName(availableLocale)}</a>
</li>
</g:each>
</ul>
</li>
</g:if>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle d-flex align-items-center" href="#" id="themeDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="Toggle theme">
<i class="bi bi-circle-half theme-icon-active"></i>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,19 @@ class GrailsGspSpec extends ApplicationContextSpec implements CommandOutputFixtu
output.containsKey("grails-app/views/notFound.gsp")
}

void "test default layout includes the language selector dropdown"() {
when:
final def output = generate(ApplicationType.WEB, new Options(DevelopmentReloading.DEVTOOLS))
final String layout = output["grails-app/views/layouts/main.gsp"]

then: "the navbar reads the i18n plugin's published available locales"
layout.contains("application.getAttribute('availableLocales')")

and: "and renders a Bootstrap dropdown that switches language via ?lang="
layout.contains("dropdown-toggle")
layout.contains('?lang=${availableLocale.toLanguageTag()}')
}

void "test default layout includes the light/dark/auto theme selector"() {
when:
final def output = generate(ApplicationType.WEB, new Options(DevelopmentReloading.DEVTOOLS))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -972,9 +972,20 @@ class FormTagLib implements ApplicationContextAware, InitializingBean, TagLibrar
* @attr name REQUIRED The name of the select
* @attr value The set locale, defaults to the current request locale if not specified
* @attr locale The locale to use for formatting the locale names. Defaults to the current request locale and then the system default locale if not specified
* @attr available If <code>true</code>, list only the locales the application is translated into
* (those with a <code>messages_*.properties</code> bundle, as published to the servlet context by
* the i18n plugin) instead of every locale the JVM knows about. Defaults to <code>false</code>.
*/
def localeSelect(Map attrs) {
attrs.from = Locale.getAvailableLocales()
def availableAttr = attrs.remove('available')
boolean availableOnly = availableAttr != null && Boolean.valueOf(availableAttr.toString())
if (availableOnly) {
def availableLocales = request.servletContext?.getAttribute('availableLocales')
attrs.from = availableLocales ?: [RCU.getLocale(request)]
}
else {
attrs.from = Locale.getAvailableLocales()
}
attrs.value = (attrs.value ?: RCU.getLocale(request))?.toString()
// set the key as a closure that formats the locale
attrs.optionKey = { it.country ? "${it.language}_${it.country}" : it.language }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.grails.web.taglib

import grails.testing.web.taglib.TagLibUnitTest
import org.grails.plugins.web.taglib.FormTagLib
import spock.lang.Specification

/**
* Tests the {@code available="true"} mode of {@code g:localeSelect}, which restricts the options to
* the locales the i18n plugin publishes to the servlet context (the app's real translations) instead
* of every locale the JVM knows about.
*/
class LocaleSelectAvailableSpec extends Specification implements TagLibUnitTest<FormTagLib> {

void 'available="true" lists only the locales published to the servlet context'() {
given:
request.servletContext.setAttribute('availableLocales',
[Locale.forLanguageTag('en'), Locale.forLanguageTag('es')])

when:
String output = applyTemplate('<g:localeSelect name="lang" available="true"/>')

then: 'the two published locales are options'
output.contains('name="lang"')
output.contains('value="en"')
output.contains('value="es"')

and: 'a locale that has no bundle is not offered'
!output.contains('value="fr"')
}

void 'without available="true" the tag still lists every JVM locale'() {
when:
String output = applyTemplate('<g:localeSelect name="lang"/>')

then:
output.contains('value="fr"')
}

void 'an explicit available="false" keeps the full JVM locale list even when locales are published'() {
given:
request.servletContext.setAttribute('availableLocales',
[Locale.forLanguageTag('en'), Locale.forLanguageTag('es')])

when:
String output = applyTemplate('<g:localeSelect name="lang" available="false"/>')

then: 'a locale outside the published list is still offered'
output.contains('value="fr"')
}

void 'available="true" falls back to the current locale when nothing is published'() {
when:
String output = applyTemplate('<g:localeSelect name="lang" available="true"/>')

then: 'no servlet-context attribute is present, so the select is not empty and not the full JVM list'
output.contains('<select')
!output.contains('value="fr"')
}

void 'the published list can drive a custom link dropdown like the create-app layout does'() {
given: 'the same servlet-context attribute the i18n plugin publishes and the create-app main.gsp reads'
request.servletContext.setAttribute('availableLocales',
[Locale.forLanguageTag('en'), Locale.forLanguageTag('es')])

when: 'the navbar snippet from the generated layout is rendered'
String output = applyTemplate('''
<g:set var="availableLocales" value="${application.getAttribute('availableLocales')}"/>
<g:if test="${availableLocales && availableLocales.size() > 1}">
<g:each in="${availableLocales}" var="availableLocale">
<a href="?lang=${availableLocale.toLanguageTag()}">${availableLocale.getDisplayName(availableLocale)}</a>
</g:each>
</g:if>
'''.stripIndent())

then: 'one ?lang= link per published locale is produced'
output.contains('href="?lang=en"')
output.contains('href="?lang=es"')
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.grails.plugins.i18n;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

/**
* Discovers the locales an application is actually translated into by scanning the
* classpath for {@code <basename>_<locale>.properties} resource bundles.
*
* <p>Unlike {@link java.util.Locale#getAvailableLocales()} (which returns every locale
* the JVM knows about), this returns only the locales that have a matching message
* bundle plus the configured default locale, making it suitable for driving a language
* selector. The result is sorted by each locale's display name in its own language and
* cached; {@link #clearCache()} forces a re-scan (used when bundles change in development).
*
* <p>By default only the application's own {@code messages_*.properties} bundles are
* scanned. When {@code includePluginBundles} is enabled, every {@code *.properties}
* bundle on the classpath is considered, so locales contributed by plugins &mdash; whose
* bundles are namespaced (e.g. {@code spring-security-core_fr.properties}) &mdash; are
* included too. Candidate suffixes are validated against the ISO language codes (and the ISO
* country codes when a country is present), so non-i18n properties files (e.g.
* {@code application.properties} or {@code foo_en_prod.properties}) are ignored. See
* {@code grails.i18n.availableLocales.includePlugins}.
*
* @since 8.0.0
*/
public class AvailableLocaleResolver {

private static final Logger log = LoggerFactory.getLogger(AvailableLocaleResolver.class);

/** The base name of an application's own message bundles ({@code messages.properties}). */
public static final String DEFAULT_BASE_NAME = "messages";

private static final String PROPERTIES_SUFFIX = ".properties";

private static final Set<String> ISO_LANGUAGES = new HashSet<>(Arrays.asList(Locale.getISOLanguages()));

private static final Set<String> ISO_COUNTRIES = new HashSet<>(Arrays.asList(Locale.getISOCountries()));

private final ResourcePatternResolver resourcePatternResolver;

private final Locale defaultLocale;

private final boolean includePluginBundles;

private volatile List<Locale> cachedLocales;

/**
* Scans only the application's own {@code messages_*.properties} bundles.
*
* @param classLoader the class loader whose classpath is scanned for message bundles
* @param defaultLocale the locale of the base {@code messages.properties} bundle,
* always included in the result (may be {@code null} to include none)
*/
public AvailableLocaleResolver(ClassLoader classLoader, Locale defaultLocale) {
this(classLoader, defaultLocale, false);
}

/**
* @param classLoader the class loader whose classpath is scanned for message bundles
* @param defaultLocale the locale of the base bundle, always included (may be {@code null})
* @param includePluginBundles whether to also consider plugin-contributed bundles (every
* {@code *.properties} on the classpath) rather than only the application's {@code messages}
*/
public AvailableLocaleResolver(ClassLoader classLoader, Locale defaultLocale, boolean includePluginBundles) {
this.resourcePatternResolver = new PathMatchingResourcePatternResolver(classLoader);
this.defaultLocale = defaultLocale;
this.includePluginBundles = includePluginBundles;
}

/**
* @return an unmodifiable, display-name-sorted list of the locales the application is
* translated into. Computed once and cached until {@link #clearCache()} is called.
*/
public List<Locale> getAvailableLocales() {
List<Locale> locales = this.cachedLocales;
if (locales == null) {
synchronized (this) {
locales = this.cachedLocales;
if (locales == null) {
locales = computeAvailableLocales();
this.cachedLocales = locales;
}
}
}
return locales;
}

/**
* Discards the cached list so the next {@link #getAvailableLocales()} re-scans the classpath.
*/
public void clearCache() {
this.cachedLocales = null;
}

private List<Locale> computeAvailableLocales() {
Set<Locale> locales = new LinkedHashSet<>();
if (this.defaultLocale != null && !this.defaultLocale.getLanguage().isEmpty()) {
locales.add(this.defaultLocale);
}
String pattern = "classpath*:" + DEFAULT_BASE_NAME + "_*" + PROPERTIES_SUFFIX;
if (this.includePluginBundles) {
pattern = "classpath*:*" + PROPERTIES_SUFFIX;
}
try {
for (Resource resource : this.resourcePatternResolver.getResources(pattern)) {
Locale locale = localeFromBundleFilename(resource.getFilename());
if (locale != null) {
locales.add(locale);
}
}
}
catch (IOException ex) {
log.warn("Unable to resolve available locales from message bundles: {}", ex.getMessage());
}
List<Locale> sorted = new ArrayList<>(locales);
sorted.sort(Comparator.comparing((Locale locale) -> locale.getDisplayName(locale)));
return Collections.unmodifiableList(sorted);
}

/**
* Extracts the locale a bundle filename encodes, or {@code null} if it is not a locale-specific
* message bundle. The base name ends at the first underscore (matching Grails' own message-source
* convention, where plugin base names use hyphens). The suffix follows the resource-bundle
* convention {@code language(_COUNTRY(_variant))} &mdash; not BCP 47 &mdash; so the language must
* be an ISO language and, when present, the country an ISO country; anything else (e.g.
* {@code foo_en_prod.properties}) is rejected rather than misparsed as a script or region.
*/
private static Locale localeFromBundleFilename(String filename) {
if (filename == null || !filename.endsWith(PROPERTIES_SUFFIX)) {
return null;
}
String base = filename.substring(0, filename.length() - PROPERTIES_SUFFIX.length());
int underscore = base.indexOf('_');
if (underscore < 0) {
return null;
}
String[] parts = base.substring(underscore + 1).split("_", 3);
String language = parts[0];
if (!ISO_LANGUAGES.contains(language)) {
return null;
}
if (parts.length == 1) {
return Locale.of(language);
}
String country = parts[1];
if (!ISO_COUNTRIES.contains(country)) {
return null;
}
return (parts.length == 2) ? Locale.of(language, country) : Locale.of(language, country, parts[2]);
}

}
Loading
Loading