闽公网安备 35020302035485号
3. PO 文件可以与在线编辑工具进行良好的配合

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();代码来完成。msgid "Hello world!" msgstr "Bonjour le monde!"es.po文件如下:
msgid "Hello world!" msgstr "¡Hola Mundo!"PO 文件存储要翻译的字符串和翻译后的字符串,语法是:
@using Microsoft.AspNetCore.Mvc.Localization; @inject IViewLocalizer;现在我们可以使用该对象来读取PO文件
<p>@Localizer["Hello world!"]</p>

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();
}
六.使用不同的复数形式添加语言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 "Views.Home.About" msgid "Hello world!" msgstr "Bonjour le monde!"
builder.Services.AddPortableObjectLocalization(options => options.ResourcesPath = "Localization");