& Lt; ABP document & gt; Localization: the content of the abp document is localized.

Source: Internet
Author: User

<ABP document> Localization: the content of the abp document is localized.

 

Document directory

 

Content of this section:

  • Introduction
  • Application Language
  • Localization Source
    • XML file
      • Register an XML localization Source
    • JSOn File
      • Register a JSON localization Source
    • Resource file
    • Custom Source
  • Obtain a local text
    • On the server
      • In the MVc Controller
      • In the MVC View
    • In Javascript
      • Format parameters
      • Default localization Source
  • Extended localization Source
  • Obtain Language
  • Best practices

 

Introduction

Any application must have at least one user interface language, and many applications may have multiple types of applications. The ABP provides a flexible localization system for an application.

 

Application Language

The first thing is to declare which languages are supported, which is completed in your module's PreInitialize method, as shown below:

Configuration.Localization.Languages.Add(new LanguageInfo("en", "English", "famfamfam-flag-england", true));Configuration.Localization.Languages.Add(new LanguageInfo("tr", "Türkçe", "famfamfam-flag-tr"));

On the server side, you can inject and use ILocalizationManager. on the client side, you can use the javascript Api's abp. localization gets the list of all available languages and the current language. famfamfam-flag-england (and tr) is a CSS class. You can modify it as needed, then, use it to display related flags on the UI.

The ABP template uses an empty system to display a language switching combo box to the user. You can learn more from the template creation and view the source code.

 

Localization Source

Localized text can be stored in different sources, and even multiple sources can be used in the same application. (If you have multiple modules, each module can define an independent localization source, or a module defines multiple sources), a localization source should implement the ILocalizationSource interface, and then it is registered in the ABP localization configuration.

Each localized source must have a unique source name. The following lists the predefined source types.

 

XML file

Localized text can be stored in XML files, which are similar to the following:

<?xml version="1.0" encoding="utf-8" ?><localizationDictionary culture="en">  <texts>    <text name="TaskSystem" value="Task System" />    <text name="TaskList" value="Task List" />    <text name="NewTask" value="New Task" />    <text name="Xtasks" value="{0} tasks" />    <text name="CompletedTasks" value="Completed tasks" />    <text name="EmailWelcomeMessage">Hi,Welcome to Simple Task System! This is a sampleemail content.</text>  </texts></localizationDictionary>

The XML file must contain the encoding (UTF-8), and the culture = "en" indicates that the XML file contains English text. The node: name attribute of the text is used to identify a text, you can use the value attribute or inner text (such as the last one) to set the value of the localized text. We create an independent XML file for each language, as shown below:

 

SimpleTaskSystem is the source name, SimpleTaskSystem. xml defines the current language. When a text is requested, the ABP obtains the text from the XML file of the current language (using Thread. currentThread to find the current language). If the text does not exist, it will find it from the XML file of the default language.

 

Register an XML localization Source

XML files can be stored in a file system or embedded into a collection.

If the XML file is stored in the file system, you can register an XML localization source as follows:

Configuration.Localization.Sources.Add(    new DictionaryBasedLocalizationSource(        "SimpleTaskSystem",        new XmlFileLocalizationDictionaryProvider(            HttpContext.Current.Server.MapPath("~/Localization/SimpleTaskSystem")            )        )    );

This is done in the PreInitialize event of a module (for more information, see the module system). The abccommand finds all the XML files in the specified folder and registers them as the localization source.

If XML is embedded into a collection, we should mark all localized XML files as embedded resources (select XML files and open the attribute window (F4) and change the generated operation to an embedded resource). Then, we can register the local source using the following method:

Configuration.Localization.Sources.Add(    new DictionaryBasedLocalizationSource(        "SimpleTaskSystem",        new XmlEmbeddedFileLocalizationDictionaryProvider(            Assembly.GetExecutingAssembly(),            "MyCompany.MyProject.Localization.Sources"            )        )    );

XmlEmbeddedFileLocalizationDictionaryProvider obtains the namespace of an xml file contained in an assembly (GetExecutingAssembly points directly to the current Assembly) and an xml file (The namespace is calculated by the following formula: Assembly name + directory level of the XML file ).

Note: Do not use the suffix when adding a suffix to an embedded XML file., such as "MySource. tr. xml ", should use a short horizontal, such as the MySource-tr.xml, because when looking for resources. it causes namespace problems.

 

JSON File

The JSON file can be used to store the text of a localized source. The following is an example of a JSON localized file:

{  "culture": "en",  "texts": {    "TaskSystem": "Task system",    "Xtasks": "{0} tasks"  }}

The JSON file should be encoded (UTF-8) and culture: "en" indicates that the JSON file contains English text. We can create a separate JSON file for each language, as shown below:

MySourceName is the source name, And MySourceName. json defines the default language, which is similar to an XML file.

 

Register a JSON localization Source

JSON files can be stored in a file system or embedded into a set of programs.

If it is stored in a file system, we can register it as follows:

Configuration.Localization.Sources.Add(    new DictionaryBasedLocalizationSource(        "MySourceName",        new JsonFileLocalizationDictionaryProvider(            HttpContext.Current.Server.MapPath("~/Localization/MySourceName")            )        )    );

This is done in the PreInitialize event of a module (for more information, see the module system). The abccommand finds all the JSON files in the specified folder and registers them as the localization source.

If JSON is embedded into a collection, all localized JSON files should be marked as embedded resources (select a JSON file and open the attribute window (F4) and change the generated operation to an embedded resource). Then, we can register the local source using the following method:

 Configuration.Localization.Sources.Add(    new DictionaryBasedLocalizationSource(        "MySourceName",        new JsonEmbeddedFileLocalizationDictionaryProvider(            Assembly.GetExecutingAssembly(),            "MyCompany.MyProject.Localization.Sources"            )        )    ); 

JsonEmbeddedFileLocalizationDictionaryProvider obtains the namespace of a json file contained in an assembly (GetExecutingAssembly points directly to the current Assembly) and a JSON file (The namespace is calculated by the following formula: Assembly name + directory level of the JSON file ).

Note: Do not add a suffix to an embedded JSON file., such as "MySource. tr. JSON ", should use a short horizontal, such as the MySource-tr.JSON, because when looking for resources. it causes namespace problems.

 

Resource file

Local files can also be stored in. in the. net Resource file, we can create a resource file for each language (right-click the project, select "add item", and find "resource file"), as shown below:

MyTexts. resx contains the default language text. MyTexts. tr. resx contains the Turkish (Turkish) language text. when we open the MyTexts. resx file, we can see all the text:

In this case, if you use the. net built-in Resource Manager to use localization, you should configure this resource file as a localization Source:

Configuration.Localization.Sources.Add(    new ResourceFileLocalizationSource(        "MySource",        MyTexts.ResourceManager        ));

The unique name of this source is MySource, and MyTexts. ResourceManager is a reference pointing to this resource manager and will be used to obtain the localized text. This configuration is completed in the PreInitialize event of a module (for more information, see the module system ).

 

Custom Source

A custom source can store text in different sources, such as a database, you can directly implement the ILocalizationSource interface or simply inherit from the DictionaryBasedLocalizationSource class (this is also used for json and xml localization sources ). Module zero is used in the database.

 

Obtain a local text

After creating a source and registering it to the ABC localization system, you can easily localize the text.

 

On the server

On the server side, we can inject ILocalizationManager and use its GetString method:

var s1 = _localizationManager.GetString("SimpleTaskSystem", "NewTask");

The GetString method obtains the string from the localization source based on the UI culture of the current thread. If no string is found, it is returned to the default language.

If no specified string is defined, it returns the humanized specified string by default and wraps it with [and] (without throwing an exception). For example, if the specified text is "thismytext ", the result will be "[This is my text]", which can be configured (Configuration can be used in PreInitialize of your module. localization ).

To obtain the source name repeatedly, You can first obtain the source and then obtain a string from the source:

var source = _localizationManager.GetSource("SimpleTaskSystem");var s1 = source.GetString("NewTask"); 

This will return the text of the current language, and there are several reloads used to obtain different languages and different formatting parameters.

If we cannot inject ILocalizationManager (possibly in a static context that cannot use dependency injection), we can simply use LocalizationHelper static class, but if possible, we can still inject and use ILocalizationManager, because LocalizationHelper is static, it is difficult to write unit tests for it.

If you need to localize an application service, Mvc controller, Razor view, or a class inherited from AbpServiceBase, you can use the L method quickly.

 

In the Mvc Controller

Localized text is usually required in the Mvc controller and view. Here is a quick method, as shown in the following example controller:

public class HomeController : SimpleTaskSystemControllerBase{    public ActionResult Index()    {        var helloWorldText = L("HelloWorld");        return View();    }}

To use the L method to localize a string, you must first provide a source name, which can be provided in the SimpleTaskSystemControllerBase shown below:

public abstract class SimpleTaskSystemControllerBase : AbpController{    protected SimpleTaskSystemControllerBase()    {        LocalizationSourceName = "SimpleTaskSystem";    }}

Note: It inherits from AbpController, so you can easily use the L method to localize text.

 

In the Mvc View

Similarly, the L method also exists in the View:

<div>    <form id="NewTaskForm" role="form">        <div class="form-group">            <label for="TaskDescription">@L("TaskDescription")</label>            <textarea id="TaskDescription" data-bind="value: task.description" class="form-control" rows="3" placeholder="@L("EnterDescriptionHere")" required></textarea>        </div>        <div class="form-group">            <label for="TaskAssignedPerson">@L("AssignTo")</label>            <select id="TaskAssignedPerson" data-bind="options: people, optionsText: 'name', optionsValue: 'id', value: task.assignedPersonId, optionsCaption: '@L("SelectPerson")'" class="form-control"></select>        </div>        <button data-bind="click: saveTask" type="submit" class="btn btn-primary">@L("CreateTheTask")</button>    </form></div>

To use it, you should let your view inherit from a base class with the specified source name:

public abstract class SimpleTaskSystemWebViewPageBase : SimpleTaskSystemWebViewPageBase<dynamic>{}public abstract class SimpleTaskSystemWebViewPageBase<TModel> : AbpWebViewPage<TModel>{    protected SimpleTaskSystemWebViewPageBase()    {        LocalizationSourceName = "SimpleTaskSystem";    }}

Configure this view base class in Web. config:

<pages pageBaseType="SimpleTaskSystem.Web.Views.SimpleTaskSystemWebViewPageBase"> 

If your solution is to create from the ABP template, all of this is done.

 

In javascript

To make it possible to localize text in javascript code, you should first add a dynamic ABP script to the page:

<script src="/AbpScripts/GetScripts" type="text/javascript"></script>

On the client side, abcwill automatically generate necessary javascript code for the localized text, and then you can easily use javascript to obtain a local text, as shown below:

var s1 = abp.localization.localize('NewTask', 'SimpleTaskSystem');

NewTask is the text name, SimpleTaskSystem is the source name, and it is the source name that does not repeat. You can first get the source and then get the text:

var source = abp.localization.getSource('SimpleTaskSystem');var s1 = source('NewTask');

 

Format parameters

The Localization method can accept additional formatting parameters, for example:

abp.localization.localize('RoleDeleteWarningMessage', 'MySource', 'Admin');//shortcut if source is got using getSource as shown abovesource('RoleDeleteWarningMessage', 'Admin'); 

If "RoleDeleteWarningMessage = 'Role {0} will be deleted'" exists, the localized text will be "Role Admin will be deleted ".

 

Default localization Source

You can set a default localization source, and then use the ABC. localization. localize method without the source name parameter:

abp.localization.defaultSourceName = 'SimpleTaskSystem';var s1 = abp.localization.localize('NewTask');

DefaultSourceName is global and can only be one source name at a time.

 

Extended localization Source

Suppose we use a module that contains the localization source, because we may need to change its localization text, add new text, or translate it into another language, so we can extend a localization source, which currently works on XML and JSON files (essentially any localization source that implements the IDictionaryBasedLocalizationSource interface ).

The ABP also defines some localization sources. For example, the Abp. Web nuget package defines a localization source named "AbpWeb", which is an embedded XML file:

The default XML file is shown below (only the first two texts are displayed ):

<?xml version="1.0" encoding="utf-8" ?><localizationDictionary culture="en">  <texts>    <text name="InternalServerError" value="An internal error occurred during your request!" />    <text name="ValidationError" value="Your request is not valid!" />    ...  </texts></localizationDictionary>

To expand the AbpWeb source, we can define an XML file. If we only want to modify the InternalServerError text, we can define the XML file as follows:

<?xml version="1.0" encoding="utf-8" ?><localizationDictionary culture="en">  <texts>    <text name="InternalServerError" value="Sorry :( It seems there is a problem. Let us to solve it and please try again later." />  </texts></localizationDictionary>

Then register it in the PreInitialize method of our module:

Configuration.Localization.Sources.Extensions.Add(    new LocalizationSourceExtensionInfo("AbpWeb",        new XmlFileLocalizationDictionaryProvider(            HttpContext.Current.Server.MapPath("~/Localization/AbpWebExtensions")            )        )    );

If you want to create an embedded XML resource file (view the local ), you can use XmlEmbeddedFileLocalizationDictionaryProvider to rewrite (merge) The base localization source and our XML file. You can also add new language files.

Note: We can use a Json file to expand the XML file, and vice versa.

 

Obtain Language

ILanguageManager is used to obtain a list of all available languages and the current language.

 

Best practices

XML files, JSON files, and resource files have their own advantages and disadvantages. We recommend that you use XML or JSON files instead of resource files because:

  • XML/JSon files are easier to edit and expand.
  • The XML/JSon file requires that the string key be provided when obtaining the localized text, instead of the attribute that needs to be compiled as the resource file, which can be seen as a disadvantage, but it can easily modify the source in the future, or even move it to a database without having to modify or write the localization code (Module-Zero implements it, A basic database is created to provide the localization source for each tenant and view the document ).

If you use XML or JSON, we recommend that you do not sort the text by name or by creation time, because when someone translates it into another language, it is easy to see which one is newly added.

 

Kid1412 Appendix: http://www.aspnetboilerplate.com/Pages/Documents/Localization

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.