Localization of ASP.NET MVC applications

    On the topic of localization, there have already been several articles on Habré, for example, Localizing ASP.NET MVC applications using a database or MVC 2: A complete guide to localization , but still the problem is still relevant.

    Most recently, we had the task of localizing (translating) the site interface into another language. Our project is being developed on ASP.NET MVC and the project has a lot of client code in JavaScript and jQuery templates. Another important point for us is the possibility of interactive work of translators, actually translating the site on the fly.

    Basically, all articles related to this topic prescribe the use of resource files, while the solution is not flexible, cumbersome, and besides, the problem of translating scripts and templates, which are a significant part of any modern web project, is not taken into account. In the end, we decided to write our own Knoema.Localization library, which we recently posted publicly. Our code is based on the wonderful development of Griffin , but has been significantly improved, it includes an interactive translation tool, as well as tools for the natural localization of JS code and templates.

    Opportunities

    The library allows you to localize:
    • Views
    • String constants in code
    • Models and text in data validation attributes
    • JavaScript text
    • JQuery Templates

    The main idea is that all localizable strings are determined by the file name or class, and then presented in the form in which they are in the project.


    Connection and configuration

    To connect the library to the project, just install the Nuget package Knoema.Localization.Mvc. To store localized data, you also need a repository implementation. In the simplest case, it is enough to connect a ready-made implementation for EF by installing the Knoema.Localization.EFProvider package. An alternative is to develop your provider by implementing a fairly simple interface ILocalizationRepository.

    In Global.asax in Application_Start () initialize the created repository:
    Knoema.Localization.LocalizationManager.Repository = new Knoema.Localization.EFProvider.LocalizationRepository();
    

    and in the RegisterRoutes method write:
    routes.IgnoreRoute("_localization/{*route}");
    

    If you use Nuget, then when adding assemblies to web.config, the following values ​​will automatically be added:

    If you are not using, then you need to add these settings manually.
    The initial configuration is ready, now I will write more about the details of use.

    View localization

    To localize views in web.config, you need to specify that LocalizedWebViewPage will be used as the base class for pages:
    
        ...
        
          ...
          

    After that, in the view code, the Html helper will be available:
    public string R(string text, params object[] formatterArguments);
    

    Example

    @R("Hello world!")


    The text can be parameterized:

    @R("Hello {0}!", username)


    Localization of string constants in code

    Lines in the code are localized using the extension:
    public static string Resource(this string value, object obj)
    

    or, if the method is static, where there is no this object, you can use:
    public static string Resource(this string value, Type type)
    

    Example

    "The given input does not refer to a valid Search.".Resource(this)
    

    Model localization

    To localize models, you must redefine the standard validation provider and metadata provider. To do this, add in Application_Start () in Global.asax:
    ModelValidatorProviders.Providers.Clear();
    ModelValidatorProviders.Providers.Add(new ValidationLocalizer());
    ModelMetadataProviders.Current = new MetadataLocalizer();
    

    All models that can be localized must be marked with the Localized attribute.

    Example

    [Localized]
    public class SignInViewModel
    {
    	[Required(ErrorMessage = "Please provide your e-mail")]
    	[Display(Name = "E-mail")]
    	public string EMail { get; set; }
    	[Required(ErrorMessage = "Please type your password")]
    	public string Password { get; set; }
    }
    

    Properties and attributes do not need to be localized separately. All metadata will be added automatically, it remains only to add the appropriate translation for them.

    Locating javascript and html templates

    String constants in javascript code are localized using the jQuery extension:
    $.localize(text, scriptSource);
    

    The extension can be connected anywhere on the page using a helper, it’s better for the entire application immediately:
    @RenderLocalizationIncludes(User.IsInRole("Admin"))	 
    

    In addition, RenderLocalizationIncludes will embed a widget on the site (provided that you are an administrator), where you can translate everything that you localized.

    Example

    $.localize("Layout options", "~/js/shared/site.js");
    

    Note

    It seemed inconvenient to us that every time you need to specify a file name. In our project we use resources minifikator the Cassette , where it is possible to add a handler for resources before they compile. A simple configuration example:
    public class CassetteConfiguration : ICassetteConfiguration
    {
    	private void CustomizeScript(ScriptBundle bundle)
    	{
    		bundle.Processor = new ScriptPipeline().Prepend(new LocalizationResourceProcessor());
    	}
    	public void Configure(BundleCollection bundles, CassetteSettings settings)
    	{
    		bundles.AddPerIndividualFile("js/shared/site.js", customizeBundle: CustomizeScript);
    	}
    }
    

    Now the long call to $ .localize ("Layout options", "~ / js / shared / site.js") can be replaced by:
    __R("Layout options");
    

    LocalizationResourceProcessor will replace __R with $ .localize and add the file name as the second parameter.

    Adding a translation

    Translation can be added directly to the site using the widget that appears in the lower left corner of the screen.

    Those representations or models that are fully translated are highlighted in gray.

    Editing:


    You can add a new language, export / import an existing one.


    In conclusion, I want to say that the library was first written for internal use, it turned out pretty well and therefore decided to publish it and write an article.

    Links:
    GitHub source code
    Knoema.Localization.Core
    Knoema.Localization.MVC
    Knoema.Localization.Cassette

    Also popular now: