4

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"];

2 Answers2

9

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

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.

lin
  • 75
  • 1
  • 8