koryakinp
koryakinp

Reputation: 4125

ASP.NET Core MVC view localization

I am using ASP.NET Core MVC and let's say I have the following Razor view:

@model AwesomeApp.ViewModels.User

<h1>
    User <span class="user">@Model.Username</span> has reached <span class="level">@Model.Level</span> level!
</h1>

Now I want to localize it:

@model AwesomeApp.ViewModels.User
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer

<h1>
    @Localizer["LevelUp", Model.Username, Model.Level]
</h1>

In my .resx file I have a resource with a key LevelUp:

User <span class="user">{0}</span> has reached <span class="level">{1}</span> level

That is working fine, but I do not want to keep HTML tags in the .resx file, I just want to keep rendered text only:

User {0} has reached {1} level!

Is there a way to do it with either IViewLocalizer or by utilizing Localization.AspNetCore.TagHelpers ?

Upvotes: 0

Views: 1039

Answers (1)

For those finding this from google now, I was able to do this in ASP.Net Core 3.1 (not sure about other versions).

Putting HTML in the parameter to the resource key, as suggested in a comment above, won't work because parameters are HTML encoded: screenshot of intellisense text

However, it is close and I was able solve it with @Html.Raw() and the Localizer.GetString() method:

@Html.Raw( Localizer.GetString( "LevelUp", $"<span class=\"user\">{Model.Username}</span>", $"<span class=\"level\">{Model.Level}</span>" ) )

And change the resx value for LevelUp to: User {0} has reached level {1}

The key here is that GetString doesn't return an LocalizedHtmlString, it returns a LocalizedString which you then can output as raw HTML.

For clarity if you're doing the format where the default language translation is the key (rather than some slug like LevelUp), it would look like this: @Html.Raw( Localizer.GetString( "User {0} has reached level {1}", $"<span class=\"user\">{Model.Username}</span>", $"<span class=\"level\">{Model.Level}</span>" ) )

And, as a bonus, you can also use GetString inside the arguments like so: @Html.Raw( Localizer.GetString( "Click {0} to do something...", $"<a href=\"whatever-link\">{Localizer.GetString("here")}</span>" )

Upvotes: 1

Related Questions