实现多语言切换
This commit is contained in:
@@ -1,10 +1,21 @@
|
||||
@page "/weather"
|
||||
@page "/{locale}/weather"
|
||||
|
||||
<PageTitle>Weather</PageTitle>
|
||||
@using Microsoft.Extensions.Localization
|
||||
@inject IStringLocalizer<Weather> L
|
||||
@inject Atomx.Admin.Client.Services.ILocalizationProvider LocalizationProvider
|
||||
|
||||
<h1>Weather</h1>
|
||||
<PageTitle>@L["weather.title"]</PageTitle>
|
||||
|
||||
<p>This component demonstrates showing data.</p>
|
||||
<h1>@L["weather.title"]</h1>
|
||||
|
||||
<p>@L["weather.summary"]</p>
|
||||
|
||||
<div style="margin-top:12px; margin-bottom:12px;">
|
||||
<strong>Quick links:</strong>
|
||||
<span style="padding-left:10px;"><NavLink href="/account/login">Login</NavLink></span>
|
||||
<span style="padding-left:10px;"><NavLink href="/counter">Counter</NavLink></span>
|
||||
</div>
|
||||
|
||||
@if (forecasts == null)
|
||||
{
|
||||
@@ -16,7 +27,7 @@ else
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Date</th>
|
||||
<th aria-label="Temperature in Celsius">Temp. (C)</th>
|
||||
<th aria-label="Temperature in Celsius">@L["weather.temperature"]</th>
|
||||
<th aria-label="Temperature in Farenheit">Temp. (F)</th>
|
||||
<th>Summary</th>
|
||||
</tr>
|
||||
@@ -36,10 +47,22 @@ else
|
||||
}
|
||||
|
||||
@code {
|
||||
[Parameter]
|
||||
public string Locale { get; set; } = string.Empty;
|
||||
private WeatherForecast[]? forecasts;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
if (LocalizationProvider != null)
|
||||
{
|
||||
LocalizationProvider.LanguageChanged += OnLanguageChanged;
|
||||
}
|
||||
|
||||
if (OperatingSystem.IsBrowser() && LocalizationProvider != null)
|
||||
{
|
||||
try { await LocalizationProvider.LoadCultureAsync(LocalizationProvider.CurrentCulture); } catch { }
|
||||
}
|
||||
|
||||
// Simulate asynchronous loading to demonstrate a loading indicator
|
||||
await Task.Delay(500);
|
||||
|
||||
@@ -53,6 +76,10 @@ else
|
||||
}).ToArray();
|
||||
}
|
||||
|
||||
private void OnLanguageChanged(object? s, string c) => _ = InvokeAsync(StateHasChanged);
|
||||
|
||||
public void Dispose() { if (LocalizationProvider != null) LocalizationProvider.LanguageChanged -= OnLanguageChanged; }
|
||||
|
||||
private class WeatherForecast
|
||||
{
|
||||
public DateOnly Date { get; set; }
|
||||
@@ -60,4 +87,13 @@ else
|
||||
public string? Summary { get; set; }
|
||||
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
|
||||
}
|
||||
|
||||
private string GetShortCulture(string current)
|
||||
{
|
||||
if (string.IsNullOrEmpty(current)) return current;
|
||||
if (current.StartsWith("zh", StringComparison.OrdinalIgnoreCase)) return "zh";
|
||||
if (current.StartsWith("en", StringComparison.OrdinalIgnoreCase)) return "en";
|
||||
var prefix = current.Split('-', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
|
||||
return prefix ?? current;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user