Alexis
Alexis

Reputation: 411

How to use localization with String.Format

I work on an Asp.net Core MVC website with localization and I've a text to display with variables inside like :

@{var item = "car"}
<h1>Max's @item is blue</h1>

but in french it's

@{var item = "la voiture"}
<h1>@item de Max est bleue</h1>

So the words's order change, I've try :

@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
    <h1>@String.Format(Localizer["Max's {0} is blue"],@item)</h1>

with a traduction :

    Max's {0} is blue => {0} de Max est bleu

but I've an error :

FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

How can I do this ?

Upvotes: 4

Views: 6591

Answers (2)

Roland
Roland

Reputation: 1010

 @Localizer["My Format {0}", myValue]

It solves the problem because that is the syntax for localizer with parameters.

Upvotes: 10

Alexis
Alexis

Reputation: 411

@Camilo Terevinto's solution work perfectly. here's the full solution if it can help anyone :

View :

@model Project.Models.item
    <h1>@String.Format(Localizer["Max's {0} is {1}"].Value, Model.Name, Model.Color)</h1>

Resx :

Max's {0} is {1} => {0} de Max est {1}

Upvotes: -1

Related Questions