Monday 23 June 2008

Explicit localization in EPiServer

This time I want to write about a feature which for sure is not new but I think many people (including myself a few days ago) are not aware of it. Explicit localization is actually a ASP.NET feature, it's nothing EPiServer specific but it can be very useful in EPiServer world. In fact it's all about one following line:


<%$ Resources: EPiServer, admin.admingroup.deletegrouptooltip %>


What it does? It will search through language files and will find a label associated with the "admin.admingroup.deletegrouptooltip" key for currently selected language. What is so cool about that? Well ... the best thing is that you can use it with labels, as a error message for validation and so on ... let me give you an example:


<asp:Label Text="<%$ Resources: EPiServer, usersettings.username %>" AssociatedControlID="UserName" runat="server" />
<asp:TextBox ID="UserName" ToolTip="<%$ Resources: EPiServer, usersettings.username %>" runat="server" />
<asp:RequiredFieldValidator ControlToValidate="UserName" ErrorMessage="<%$ Resources: EPiServer, login.error.username %>" runat="server"/>


How can you set for example localized tool tip for a button not using that approach? I guess the only option is to do that in code behind file in a following way:


UserName.ToolTip = Translate("/usersettings/username");


It's only one additional line ... but having all settings for the control in one place gives you cleaner code, so in the end less chances that you will overlook something. Moreover if you make a mistake typing the label key, you can correct it and see the results with recompiling the code which can save lots of time.

You can find many examples of this syntax (including the one which I used here) just by checking EPiServer's Public Templates.

2 comments:

Anonymous said...

Hello Marek,

you could avoid the code behind if you embedded the code directly:

<%= Translate("/usersettings/username") %>

So for example do
<asp:Label Text="<%= Translate("/usersettings/username") %>"
...

that said, I still prefer having code in code behind (isn't that single line of code just beautiful in its simplicity - not cluttering the aspx with all those percent and dollar signs? ;) ), rahter than mixing it in with the aspx.

But agreed, it's just a matter of taste.

Blotko said...

Hi Adam,

Well, the problem with this example is that it doesn't work, the parser error message is:

"Server tags cannot contain <% ... %> constructs"

In terms of having code in code behind file ... like you said, it's a matter of taste.

But in my opinion setting error message is a part of presentation layer so I don't think it should be mixed with code behind code. Also, it enables designers to easily change message key if needed without any problems.