5

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

1

2 Answers 2

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

since this is getting more upvotes then I could ever imagine I would strongly suggest you check out the blog post of the other answer, although my answer here is working it requires some coding, if you implement the blog post, resources will become automatically available to your js which is more desirable in some cases
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.

1 Comment

This should be a comment under the question instead, not enough detail for an answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.