如何轻松地本地化视图(只有.cshtml和该文件中的javascript )。请帮帮我,我已经花了大约5个小时,结果已经0了,官方文档太复杂了,https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-2.1 --一切都过时了。
我不得不为resx文件创建一个名称。
视图称为IndexPage.cshtml,资源文件称为SharedResource.en-US.resx
用这个
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
<p>@Localizer["Hello"]</p>给我打个招呼,但不是这个的翻译。
发布于 2020-02-11 17:51:22
它打印Hello的原因是因为它cannot find匹配的the class or view you want to localize本地化资源文件,当它找不到资源名称/键时,它将按原样打印文本(键)。
本地化有两种方法:
( A)如果您决定采用正式文档(using Localizer/IStringLocalizer)中提到的方式,则需要执行以下操作:
is
.resx files 放入其中--您需要命名您的
.resx files,以模拟您想要本地化的相关view/class file的路径。
例如:如果您有一个带有HomeController的Index action,并且您有一个位于Views/Home/Index.cshtml下面的索引视图,那么您需要将您的resx file命名为: views.home.index.en-US.resx
或者您可以将create same folder structure作为资源文件夹中的views/controller,例如:Resources/Views/Home/Index.en.resx。
在您的
//in your ConfigureServices method
services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; });
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();以及:
//in your Configure method
var supportedCultures = new[]
{
//add the cultures you support..
new CultureInfo("en-US"),
new CultureInfo("fr"),
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
// Set the default culture.
DefaultRequestCulture = new RequestCulture("en-US"),
// Formatting numbers, dates, etc.
SupportedCultures = supportedCultures,
// UI strings that we have localized.
SupportedUICultures = supportedCultures
});当请求出现时,
specific middleware来决定使用哪种区域性- `QueryStringRequestCultureProvider`.
- `CookieRequestCultureProvider`. Most apps uses this mechanism to persist the user culture.
- `AcceptLanguageHeaderRequestCultureProvider`.
运行应用程序并使用https://localhost:5001/?culture=fr进行测试,例如:
注意:您需要一个
culture fallback behavior,它可以通过一个没有.Language_Code前缀的.resx文件来处理任何不受支持的区域性,例如:views.home.index.resx,它基本上包含应用程序的主要语言。
( B)如果你觉得A方法太过分了:
如果您只想拥有特定数量的.resx文件,例如:SharedResource.resx、SharedResource.fr.resx、Messages.resx、Messages.fr.resx和Errors.resx、Errors.fr.resx,那么您可以在Resources folder中创建这些.resx files。
然后在你的startup.cs
//in your ConfigureServices method
services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; });
services.AddMvc();以及:
//in your Configure method
var supportedCultures = new[]
{
//add the cultures you support..
new CultureInfo("en-US"),
new CultureInfo("fr"),
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
// Set the default culture.
DefaultRequestCulture = new RequestCulture("en-US"),
// Formatting numbers, dates, etc.
SupportedCultures = supportedCultures,
// UI strings that we have localized.
SupportedUICultures = supportedCultures
});最后,您可以使用资源文件名访问资源文件,例如:@SharedResource.Hello
注意:您需要参考
_ViewImports.cshtml中的参考资料才能在视图中使用它们。
我知道这是一个很长的答案,但我想为您提供两种不同的方法,以便您可以决定哪种方法最适合您的用例。
https://stackoverflow.com/questions/60170196
复制相似问题