728x90
728x170

Culture 선택기 만드는 방법입니다.

1. index.html 에 script 추가

<script>
    window.blazorCulture = {
        get: () => localStorage['BlazorCulture'],
        set: (value) => localStorage['BlazorCulture'] = value
    };
</script>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>Blazor.LocalizationTest</title>
    <base href="/" />
    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
    <link href="css/app.css" rel="stylesheet" />
    <link rel="icon" type="image/png" href="favicon.png" />
    <link href="Blazor.LocalizationTest.styles.css" rel="stylesheet" />
</head>

<body>
    <div id="app">
        <svg class="loading-progress">
            <circle r="40%" cx="50%" cy="50%" />
            <circle r="40%" cx="50%" cy="50%" />
        </svg>
        <div class="loading-progress-text"></div>
    </div>

    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="" class="reload">Reload</a>
        <a class="dismiss">🗙</a>
    </div>
    <script src="_framework/blazor.webassembly.js"></script>

    <!--culture change-->
    <script>
        window.blazorCulture = {
            get: () => localStorage['BlazorCulture'],
            set: (value) => localStorage['BlazorCulture'] = value
        };
    </script>
</body>

</html>


2. CultureSelector.razor 파일 추가

@using Microsoft.AspNetCore.Components;
@using Microsoft.JSInterop;
@using System.Globalization;

<strong>Culture:</strong>
<select class="form-control" @bind="Culture" style="width:300px; margin-left:10px;">
    @foreach (var culture in cultures)
    {
        <option value="@culture">@culture.DisplayName</option>
    }
</select>

@code{
    [Inject]
    public NavigationManager NavManager { get; set; }
    [Inject]
    public IJSRuntime JSRuntime { get; set; }

    CultureInfo[] cultures = new[]
    {
        new CultureInfo("ko-kr"),
        new CultureInfo("en-US")
    };

    CultureInfo Culture
    {
        get => CultureInfo.CurrentCulture;
        set
        {
            if (CultureInfo.CurrentCulture != value)
            {
                var js = (IJSInProcessRuntime)JSRuntime;
                // change culture
                js.InvokeVoid("blazorCulture.set", value.Name);
                // refresh
                NavManager.NavigateTo(NavManager.Uri, forceLoad: true);
            }
        }
    }
}


3. MainLayout.razor 에 CultureSelector 추가

@inherits LayoutComponentBase

<div class="page">
    <div class="sidebar">
        <NavMenu />
    </div>

    <main>
        <div class="top-row px-4">
            <CultureSelector />
        </div>

        <article class="content px-4">
            @Body
        </article>
    </main>
</div>


4. Program.cs 코드 추가

using System.Globalization;

using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.JSInterop;

namespace Blazor.LocalizationTest
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("#app");
            builder.RootComponents.Add<HeadOutlet>("head::after");

            builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

            // Localization
            builder.Services.AddLocalization();

            var host = builder.Build();

            // Localization Selector ==>
            var jsInterop = host.Services.GetRequiredService<IJSRuntime>();
            var result = await jsInterop.InvokeAsync<string>("blazorCulture.get");

            CultureInfo culture;

            if (result != null)
            {
                culture = new CultureInfo(result);
            }
            else
            {
                // Default
                culture = new CultureInfo("ko-KR");
            }

            CultureInfo.DefaultThreadCurrentCulture = culture;
            CultureInfo.DefaultThreadCurrentUICulture = culture;
            // Localization Selector <==
            
            await host.RunAsync();
        }
    }
}

 

5. 프로젝트 파일에서 아래내용을 추가합니다.

<BlazorWebAssemblyLoadAllGlobalizationData>true</BlazorWebAssemblyLoadAllGlobalizationData>

<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <BlazorWebAssemblyLoadAllGlobalizationData>true</BlazorWebAssemblyLoadAllGlobalizationData>
  </PropertyGroup>
.....

결과

소스

https://github.com/kei-soft/Blazor.AppTest/tree/master/Blazor.LocalizationTest

 

GitHub - kei-soft/Blazor.AppTest

Contribute to kei-soft/Blazor.AppTest development by creating an account on GitHub.

github.com

 

728x90
그리드형
Posted by kjun
,