0

I am trying to make my app international with multiple language support. I am using the resource file approach. So far so good, but is there a way to use the resource strings in my JS file?

Can I access them in JS file or it is not possible?

mohsinali1317
  • 4,255
  • 9
  • 46
  • 85
  • possible duplicate of [How to use .net Resource files in javascript](http://stackoverflow.com/questions/3785568/how-to-use-net-resource-files-in-javascript) – Alberto Mar 10 '15 at 13:37
  • I have seen that post but it doesn't gives an answer to what I need. The ajax solution proposed there would be like spamming the server. – mohsinali1317 Mar 10 '15 at 13:41
  • Check this: http://stackoverflow.com/questions/940769/use-asp-net-resource-strings-from-within-javascript-files and more in particular Domenic's answer. Hope this can help you! – Alberto Mar 10 '15 at 13:47

2 Answers2

0

The common approach to do localization in JavaScript is to override the fields by a localized JavaScript file which is loaded after the main one.

i.e your main app.js or whatever you call it declares an object:

DateTime = {}
DateTime.days = ["Sunday", "Monday", "Tuesday", ...];
DateTime.dateFormat = "m/d/Y";
DateTime.getToday = function(date) {
    var dayOfWeek = ...;
    return DateTime.days[dayofWeek];
}

Then in your localization file, let's call it locale_de-de.js you add

DateTime.days = ["Sonntag", "Montag", "Dienstag", ...];
DateTime.dateFormat = "d.m.Y";

That's also how most javascript frameworks (i.e. ExtJS, AngularJS) do their localizations. In your templates just do

@Scripts.Render("~/bundles/app")
@Scripts.Render("~/bundles/locale_de-de")

No need for resource strings and "parsing" your JavaScript files to replace the values with ones from Resource strings

Tseng
  • 61,549
  • 15
  • 193
  • 205
0

Simplest way I have found is to create a javascript key-value pair in _Layout.cshtml using razor with resources:

var resourceData = { 'register_account_pesel_incorrect': '@LanguageResources.register_account_login_incorrect', 'register_account_password_incorrect': '@LanguageResources.register_account_password_incorrect' }

Then in your *.js file you simply use the resourceData like this:

options.messages["isLogin"] = resourceData['register_account_login_incorrect'];

Or even simplier:

options.messages["isLogin"] = resourceData.register_account_login_incorrect;
DiSaSteR
  • 608
  • 6
  • 11