-
-
Notifications
You must be signed in to change notification settings - Fork 974
Add available-locale discovery and a language selector to i18n #15940
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: 8.0.x
Are you sure you want to change the base?
Changes from all commits
d62ae0a
b756b53
081acf9
8f9d7aa
170ae02
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 == currentLocale ? ' active' : ''}" href="?lang=${availableLocale.toLanguageTag()}">${availableLocale.getDisplayName(availableLocale)}</a> | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Two behavioural nits (both also apply to the identical copy in
|
||
| </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> | ||
|
|
||
| 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,173 @@ | ||
| /* | ||
| * 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 — whose | ||
| * bundles are namespaced (e.g. {@code spring-security-core_fr.properties}) — are | ||
| * included too. Candidate suffixes are validated against {@link Locale#getISOLanguages()} | ||
| * so non-i18n properties files (e.g. {@code application.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 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), and the suffix must be a recognised language. | ||
| */ | ||
| 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 code = base.substring(underscore + 1); | ||
| if (code.isEmpty()) { | ||
| return null; | ||
| } | ||
| Locale locale = Locale.forLanguageTag(code.replace('_', '-')); | ||
| return ISO_LANGUAGES.contains(locale.getLanguage()) ? locale : null; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Only the language subtag is validated, so with
Since |
||
| } | ||
|
|
||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This paragraph ends with "build your own switcher:" but the
g:eachexample it introduces is pushed below the plugin-discovery paragraph and the YAML block. Reordering to intro → example → plugin-discovery paragraph → YAML would read better.