How to set up a backup resource file for views

Using IViewLocalizer , I would like to localize the view with the default resource file or backup for words and phrases that appear on several pages, for example, edit, add, delete ... I do not want to add these duplicate phrases in the resource file of all views, where they appear, so the backup recursive file really comes in handy, but I just can't find a solution on how to do this.

I am currently using @inject IViewLocalizer Localizer in my views, and I am getting localized phrases with @Localizer["ResourceName"] from resource files:

Resources / Views / {ControllerName} / {ViewName}. {} LangCode.resx

This is great for every single view and partial view. Now, I would like to have a resource file either in the Resources/Views folder, or Resources , which acts as a backup resource file.

So, for example, if I say @Localizer["Edit"] in one of my views, and the "Change" resource is not found in Resources/Views/{ControllerName}/{ViewName}.{langCode}.resx or Resources/Views/{ControllerName}/{ViewName}.resx , it reverts to this file by default, so I can use it for all my views that need a Resource.

I already tried with Resources/Resource.{langCode}.resx , but it seems to have no effect.

+5
source share
1 answer

I had a similar problem when I started with localization. If your site has many repeating phrases and words, it’s best to place them in a SharedResource file.

Do this by creating the SharedResource.[LANG_CODE].resx in the Resources folder. Then you need to create a dummy class that you call SharedResource , and put it in the root of the project namespace. Therefore, if your project is called LocalizationTest , then the class will look something like this:

 namespace LocalizationTest { public class SharedResource { } } 

Then all you have to do to access the shared resource in your model or view is to create an IStringLocalizer<SharedResources> and use it. Like this:

 public class HomeController : Controller { private readonly IStringLocalizer<HomeController> _localizer; private readonly IStringLocalizer<SharedResource> _sharedLocalizer; public HomeController(IStringLocalizer<HomeController> localizer, IStringLocalizer<SharedResource> sharedLocalizer) { _localizer = localizer; _sharedLocalizer = sharedLocalizer; } public IActionResult Index() { ViewData["message"] = _sharedLocalizer["Hello!"]; return View(); } } 

Or in the view: @inject IViewLocalizer Localizer @inject IStringLocalizer SharedLocalizer

 @{ ViewData["Title"] = SharedLocalizer["Hello!"]; } <h1>@Localizer["Welcome message"]</h1> 

I skipped the import and used the instructions for brevity.

You can find more detailed information about SharedResource and general localization here: Microsoft documentation or in the answer to the question that I posted here My questions and answers .

0
source

All Articles