• .NET Core如何使用PO文件实现本地化(多语言)功能
  • 发布于 2个月前
  • 177 热度
    0 评论
  • DuXing
  • 7 粉丝 36 篇博客
  •   
可移植对象文件通常也称为 PO 文件,是基于文本文件,其中包含原始未翻译字符串与其相应翻译之间关系的条目。它们可以替换资源文件,用于ASP.NET Core 中构建的网站进行本地化。相比资源文件使用PO文件有如下几个优点:
1. PO 文件支持附属形式,我将在教程的后半部分进行解释
2. PO 文件不像 .resx 文件那样需要编译

3. PO 文件可以与在线编辑工具进行良好的配合


一. 引用包OrchardCore.Localization.Core
首先你需要引用OrchardCore.Localization.Core包,使用vs引用该包


2 在启动项中配置Website使用本地化

在启动项中添加如下代码:
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc.Razor;
using System.Globalization;
using OrchardCore.Localization.PortableObject;

var builder = WebApplication.CreateBuilder(args);
// 堆代码 duidaima.com
// Add services to the container.
builder.Services.AddControllersWithViews()
                .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
builder.Services.AddPortableObjectLocalization();
builder.Services.Configure<RequestLocalizationOptions>(options =>
{
    var supportedCultures = new[]
    {
            new CultureInfo("en-US"),
            new CultureInfo("fr"),
            new CultureInfo("es")
        };
    options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRequestLocalization();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
在上面代码中我指定网站支持3种语言, 它将使用PO文件,我们通过使用builder.Services.AddPortableObjectLocalization();来实现。接下来,我指定RequestLocalization中间件通过客户端提供的请求自动设置文化信息,可以使用app.UseRequestLocalization();代码来完成。

三.法语和西班牙语创建PO文件
在Visual Studio中创建两个文本文件,一个是法语另一个是西班牙语:
1. fr.po
2. es.po

fr.po 文件如下:
msgid "Hello world!"
msgstr "Bonjour le monde!"
es.po文件如下:
msgid "Hello world!"
msgstr "¡Hola Mundo!"
PO 文件存储要翻译的字符串和翻译后的字符串,语法是:
msgid: 要翻译的字符串
msgstr: 翻译后的字符串
这里PO文件包含的翻译的字符串"Hello world!”
fr.po文件被使用如果请求文化是fr-FR,fr-CA等,类似"es.po"文件被使用如果请求文化"es-MX",'es-US'等

四.从视图中读取PO文件
我们使用IViewLocalizer 对象读取PO文件,在视图文件中注入该对象
@using Microsoft.AspNetCore.Mvc.Localization;
@inject IViewLocalizer;
现在我们可以使用该对象来读取PO文件
<p>@Localizer["Hello world!"]</p>

测试
运行应用程序在浏览器的url后面添加?culture=fr, 你将会在浏览器中看到Hello world

五. 从控制器中读取PO文件
我们可以使用IStringLocalizer对象在控制器中读取PO文件,在Controller中使用依赖注入获取IStringLocalizer 对象,并且可以在Action方法中使用它
private readonly ILogger<HomeController> _logger;
private readonly IStringLocalizer<HomeController> _localizer;
public HomeController(IStringLocalizer<HomeController> localizer,ILogger<HomeController> logger)
{
    _localizer = localizer;
    _logger = logger;
}
public IActionResult Index()
{
   string translatedString = _localizer["Hello world!"];
   return View();
}
六.使用不同的复数形式添加语言
在es.po中添加如下字符串:
msgid "There is one item."
msgid_plural "There are {0} items."
msgstr[1] "French text for first plural"
msgstr[2] "French text for second plural"
接下来在视图中添加如下代码:
<p>@Localizer.Plural(1, "There is one item.", "There are {0} items.")</p>
<p>@Localizer.Plural(2, "There is one item.", "There are {0} items.")</p>
视图将显示如下:
French text for first plural
French text for second plural
七.在PO文件的入口处使用msgctxt限制范围
"msgctxt" 条目用于在 PO 文件中限定条目仅适用于特定的类或视图,例子:当我在fr.po文件中添加下面问题,该文件本地化只适用于About视图
msgctxt "Views.Home.About"
msgid "Hello world!"
msgstr "Bonjour le monde!"

八.PO 文件的位置
我们可以使用下面代码来改变PO文件的位置
builder.Services.AddPortableObjectLocalization(options => options.ResourcesPath = "Localization");


用户评论