'How to use resx file in javascript file. .net core 3.1 mvc
I'am developing multi language web site with .net core mvc. I used Microsoft.AspNetCore.Mvc.Localization.IHtmlLocalizer.
This code is work fine in .cshtml for me
@inject Microsoft.AspNetCore.Mvc.Localization.IHtmlLocalizer<ExampleProject.WEB.Controllers.HomeController> localizer
@localizer["NotificationManage"]
Also works between <script> tags in _Layout page
alert('@localizer["NotificationManage"]');
But don't working in js file.
How to use Resx file in javascript file.?
What another best to way make multi language to javascript?
alert('@localizer["NotificationManage"]');
Not working for me.
Alert Result is:@localizer["NotificationManage"];
Solution 1:[1]
One possible solution is to define your translations as a global variable on the window outside your script
<script>
var translations = {
notification: '@localizer["NotificationManage"]'
}
</script>
<script type="text/javascript" src="pathtoscript.js"></script>
then inside your script you go
alert(window.translations.notification);
If any better solution is given here I'm happy to hear, because we use it this way in production
Solution 2:[2]
Another approach we could consider is to create a custom tag helper to convert the resource file contents to a global javascript object and then this variable object can be directly accessed in the external js files
It is mentioned in detail in this blog javascript localization worth a read.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | lin |
