---
title: "ウォークスルー:言語切り替えコンポーネントの作成"
slug: "walkthrough--creating-a-language-switcher-component"
abstract: "レンダリングホストで言語スイッチャーコンポーネントを作成し、ユーザーが表示する言語を選択できるようにする方法。"
---
# ウォークスルー:言語切り替えコンポーネントの作成

> !重要以前にアプリを統合していた場合、それは旧版のASP.NETコアレンダリングSDK(バージョン22以前)を使用しています。このSDKは更新を受け取っていないため、[最新のバージョンへのアップグレード](https://doc.sitecore.com/xmc/en/developers/asp-net/latest/asp-net-core-sdk/upgrade-from-v22.html) をお勧めします。

このトピックでは、ASP.NETコアのローカル化およびルーティング機能を用いて、ASP.NETコアレンダリングホストに言語切り替えコンポーネントを実装する方法を説明します。

> !注このウォークスルーは、MapSitecoreLocalizedRoute拡張を使ってルーティングエンドポイントを設定するか、レイアウトサービスに要求するアイテムパスを示すsitecoreRouteルート値と、目的言語を示すcultureルート値を使って設定することを前提としています。詳細については、[Sitecoreレンダリングエンジン](https://doc.sitecore.com/xp/ja/developers/hd/19/sitecore-headless-development/asp-net-core-rendering-engine.html "ASP.NET Core Rendering Engine")を参照してください。

このウォークスルーでは、以下の方法を説明します:

-   [Viewコンポーネントを作成する](https://doc.sitecore.com/xp/ja/developers/hd/19/sitecore-headless-development/walkthrough--creating-a-language-switcher-component.html#UUID-5365b8c2-57b7-f0c1-d0fe-35713b0b8978_section-idm231968831467268 "Create the View component")
-   [Sitecoreの言語とコンテンツの追加](https://doc.sitecore.com/xp/ja/developers/hd/19/sitecore-headless-development/walkthrough--creating-a-language-switcher-component.html#UUID-5365b8c2-57b7-f0c1-d0fe-35713b0b8978_section-idm231968838306676 "Add Sitecore languages and content")
-   [言語項目のシリアライズ設定(任意)](https://doc.sitecore.com/xp/ja/developers/hd/19/sitecore-headless-development/walkthrough--creating-a-language-switcher-component.html#UUID-5365b8c2-57b7-f0c1-d0fe-35713b0b8978_N1598442734135 "Configure serialization for language items (optional)")

## Viewコンポーネントを作成する

この例では [、ASP.NETコアビューコンポーネント](https://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-3.1) を使って言語スイッチャーのロジックと表示をカプセル化しています。その後、アプリケーションの該当する場所にビューコンポーネントを追加できます。

ビューコンポーネントを作成するには:

1.  [Getting Startedガイド](https://doc.sitecore.com/xp/ja/developers/hd/19/sitecore-headless-development/walkthrough--using-the-getting-started-template.html "Walkthrough: Using the Getting Started template")に記載されているように、ASP.NETコアベースのソリューションを作成・開始してください。
    
2.  Visual Studioでは、renderingプロジェクトでStartup.csクラスを開いてください。
    
    > !注このクラスには、依存注入を通じて言語切り替え者にASP.NETコアRequestLocalizationOptionsを利用可能にするためにいくつかの変更が必要です。
    
3.  ConfigureServices方法では、以下のローカリゼーション設定登録を追加し、この例ではドイツ語、英語、日本語の3言語とSitecore URLベースの文化解決を可能にします。
    
    // You need to configure localization options here so you can access them in your language switcher component
    services.Configure<RequestLocalizationOptions>(options =>
    {
     // If you add languages in Sitecore that this site/rendering host should support, then add them here.
     var supportedCultures = new List<CultureInfo> { new CultureInfo(\_defaultLanguage), new CultureInfo("de-DE"), new CultureInfo("ja-JP") };
     options.DefaultRequestCulture = new RequestCulture(\_defaultLanguage, \_defaultLanguage);
     options.SupportedCultures = supportedCultures;
     options.SupportedUICultures = supportedCultures;
    
     // Resolve culture through the standard Sitecore URL prefix and query string (sc\_lang).
     options.UseSitecoreRequestLocalization();
    });
    
4.  Configure方法では、既存のapp.UseRequestLocalization呼び出しを削除し、よりシンプルなものに置き換えます。
    
    // Enable ASP.NET Core localization, required for Sitecore content localization.
    app.UseRequestLocalization();
    
5.  renderingプロジェクトのModelsフォルダに、言語スイッチャー用の新しいモデルクラスを追加します。このクラスは現在および利用可能な言語を出力します。クラスに以下のコードを追加します:
    
    using System.Collections.Generic;
    using System.Globalization;
    
    namespace MyProject.Models
    {
     public class LanguageSwitcherModel
     {
     public CultureInfo CurrentUICulture { get; set; }
     public List<CultureInfo> SupportedCultures { get; set; }
     public string CurrentSitecoreRoute { get; set; }
     }
    }
    
6.  renderingプロジェクト内にViewComponentsという新しいフォルダを作成し、そのフォルダ内に新しいView Componentクラスを作成します。このクラスは、設定された言語、現在の言語、現在のルートに基づいてモデルを配置します。クラスに以下のコードを追加します:
    
    using MyProject.Models;
     using Microsoft.AspNetCore.Builder;
     using Microsoft.AspNetCore.Localization;
     using Microsoft.AspNetCore.Mvc;
     using Microsoft.Extensions.Options;
     using System.Linq;
     using System.Threading.Tasks;
    
     namespace MyProject.ViewComponents
     {
     public class LanguageSwitcherViewComponent : ViewComponent
     {
     private readonly IOptions<RequestLocalizationOptions> \_localizationOptions;
    
     public LanguageSwitcherViewComponent(IOptions<RequestLocalizationOptions> localizationOptions)
     {
     \_localizationOptions = localizationOptions;
     }
    
     public async Task<IViewComponentResult> InvokeAsync()
     {
     var cultureFeature = HttpContext.Features.Get<IRequestCultureFeature>();
     var languageSwitcherModel = new LanguageSwitcherModel
     {
     SupportedCultures = \_localizationOptions.Value.SupportedCultures.ToList(),
     CurrentUICulture = cultureFeature.RequestCulture.Culture,
     CurrentSitecoreRoute = this.HttpContext.Request.RouteValues"sitecoreRoute"?.ToString() ?? ""
     };
     return View(languageSwitcherModel);
     }
     }
     }
    
7.  renderingプロジェクトでコンポーネントのビュー用に新しいフォルダパスを作成します。Views/Shared/Components/LanguageSwitcher。フォルダ内にDefault.cshtmlという名前のRazorビューを作成します。このビューはモデルを使って言語スイッチャーをレンダリングします。ビューに以下のコードを追加します:
    
    @model LanguageSwitcherModel
    
    <ul id="language-switcher">
    @foreach (var culture in Model.SupportedCultures)
    {
     <li>
     @if (Model.CurrentUICulture.Name == culture.Name)
     {
     <strong>@culture.DisplayName</strong>
     }
     else
     {
     <a asp-route-culture="@culture.Name" asp-route-sitecoreRoute="@Model.CurrentSitecoreRoute">@culture.DisplayName</a>
     }
     </li>
    }
    </ul>
    
8.  Views/\_ViewImports.cshtmlビューで、このプロジェクトのカスタムビューコンポーネントを[タグヘルパー](https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro?view=aspnetcore-3.1)として使用できるようにするために、次の行を追加してください:
    
    @addTagHelper \*, MyProject
    
9.  Sitecoreロゴの下に言語切り替え器をデフォルトビュー( Views/Default/Index.cshtml )に追加してください:
    
    <div id="Header">
     <img src="https://doc.sitecore.com/img/sc/_logo.png" alt="Sitecore" id="scLogo">
     <vc:language-switcher></vc:language-switcher>
    </div>
    
10.  レンダリングされたサイト(www.myproject.localhost)をリフレッシュして変更点を確認してください。言語を切り替えることは可能ですが、例えばドイツ語や日本語のコンテンツはまだ利用できません。
     

> !重要エラーが発生した場合は、レンダリングホストログでコンパイルエラーを確認してください。PowerShellで、次のように入力してください: docker-compose logs -f rendering。

## Sitecoreの言語とコンテンツの追加

Sitecoreの言語とコンテンツを追加するには:

1.  CM環境(cm.myproject.localhost)にログインし、Launchpadからコンテンツエディターを開きます。
2.  /sitecore/system/languagesの下に、例えばドイツ語(ドイツ)や日本語(日本)などの言語を追加します。このプロセスでde-DEとja-JPの言語項目が作成されます。
3.  /sitecore/content/MyProject/Home/Contentコンテンツ項目に移動し、これらの新しい言語の言語バージョンを作成し、**タイトルフィールドに**関連するコンテンツを入力します。例えば:
    -   ドイツ語: *ハロー!*
    -   日本語: *こんにちは*
4.  言語の追加や内容の変更を公開してください。
5.  レンダリングしたサイトに行ってください。言語を切り替えたときに言語固有のコンテンツを見ることができます。

## 言語項目のシリアライズ設定(任意)

本番環境では、作成した言語項目をシリアライズモジュールに含める必要があります。 en項目はSitecoreが付属しているため、ルールで無視できます。

言語項目のシリアライズを設定するには:

1.  src\\Items.module.jsonでは、/sitecore/system/Languagesを含む を加えます:
    
    {
     "name": "languages",
     "path": "/sitecore/system/languages",
     "rules": 
     {
     "path": "/en",
     "scope": "ignored"
     }
     
     }
    
2.  言語項目やサイト内容の変更をシリアライズするには、[Sitecore CLI](https://doc.sitecore.com/xp/en/developers/102/developer-tools/sitecore-command-line-interface.html)からdotnet sitecore ser pullを実行してください。