Razor.Templating.Core
Razor.Templating.Core copied to clipboard
Support MVC view localization
Hello,
After configuring:
services.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
services.AddRazorTemplating();
...
app.UseRequestLocalization("fr");
MVC will locate and use the view Views/Home/Index.fr.cshtml since the locating mechanism is searching for the correct view file using the Controller and View names, but _razorTemplateEngine.RenderAsync("/Views/Home/Index.cshtml") obviously doesn't support localization.
So one way is to explicitly render /Views/EmailTemplates/ConfirmEmail.fr.cshtml which is totally lame, but a better way will be to do all that automatically. So a French user registering the web app will receive the French confirmation email.
It will be awesome if localization support can be added, my guess by internally detecting AddViewLocalization and LanguageViewLocationExpanderFormat.Suffix, and when rendering maybe use LanguageViewLocationExpander to yield all possible localized views and FindView until found. I guess /Views/Home/Index.cshtml can be internally transformed to /Views/Home/{0}.cshtml for this case (ExpandViewLocations).
Any thoughts?
Hi @superware, thanks for raising this issue. Yes, this may make sense for the web apps. I haven't worked on localization before. So I'll need to play around with this a bit to see how this can be incorporated into this library.
Hi @soundaranbu, that will be great. IMHO it should be quite easy, the bottom line is looping through possible view-expanded locations until the first one is found - and use that one for rendering.
So if view-localization is enabled (either through the framework or through configuring Razor.Templating.Core), then the view name should be extracted ([^/]+)\.cshtml, templated /Views/Home/{0}.cshtml, expanded /Views/EmailTemplates/{0}.fr.cshtml, formatted /Views/EmailTemplates/ConfirmEmail.fr.cshtml and checked for existance.
Shouldn't be a breaking change since if no localized/expanded view is found then the original view will be used.
Thank you for your great work.
Hey @superware, I'm pleased to share that the prerelease package has been published with the fix if you want to give it a try
https://github.com/soundaranbu/Razor.Templating.Core/releases/tag/v2.1.0-rc.1
You can also find the usage here https://github.com/soundaranbu/Razor.Templating.Core/blob/fc7d2cf8b83f63b1b705e5cffabf041759c4c7cc/examples/Mvc/ExampleWebApp.Net6_0/Controllers/HomeController.cs#L19 where you can specify the view name without the .cshtml and it will use the localized views based on the request. This works the same way as the MVC. Please note that this is not supported for non MVC based applications.
This is now released in v2.1.0. Thanks for raising this issue :)
Wow, that's a great addition! Since I've already implemented my own, I'll try it later when I have time. Thank you.