LazZiya / XLocalizer

Localizer package for Asp.Net Core web applications, powered by online translation and auto resource creating.
https://docs.ziyad.info
129 stars 14 forks source link

IStringLocalizer missing? #10

Closed morgrowe closed 3 years ago

morgrowe commented 3 years ago

.NET 5 XLocalizer 1.0.0

I'm really excited about being able to store my resources in a database instead of a .resx file.

I followed these instructions to get the XDbResources and XDbCultures tables in my database with seeded data. That worked.

Seeded data

I then wanted to see it pulling the translations from my database, so I went to my _ViewImports.cshtml file and added:

@addTagHelper *, XLocalizer.TagHelpers

I then went to my Index.cshtml file and added the following line to the top (I'd usually add it to _ViewImports, but it didn't work):

@inject IStringLocalizer _localizer

But it doesn't seem to find IStringLocalizer. I had a quick search in the LaZiya/XLocalizer.TagHelpers for the interface, but couldn't find it. Has it been renamed? I got the instructions from: https://docs.ziyad.info/en/XLocalizer/v1.0/localizing-views.md (right at the bottom).

Reference error

The error is:

The type or namespace name 'IStringLocalizer' could not be found

I may be doing something completely stupid, but would appreciate your insight.

Thanks as always, Morgan

LazZiya commented 3 years ago

Hi @morgrowe

If you want to inject IStringLocalizer to the views you need to add the namespace:

@using Microsoft.Extensions.Localization
@inject IStringLocalizer _localizer

<h1>@_localizer["Welcome"]</h1>

btw, XLocalizer offers more elegant way to localize views, as you already saw in the docs, you can use XLocalizer.TagHelpers as below:

<h1 localize-content>Welcome</h1>

I hope this will help :)

BR, Ziya

morgrowe commented 3 years ago

I knew I was doing something silly! After adding the using statement, it worked.

I like using localize-content, but sometimes I need to add localized strings to other attributes. I can see there's a way of localizing the title attribute (localize-att-title), but not sure how I'd do it with a custom data- attribute or the alt attribute, so I usually go with @_localizer[""] to keep things consistent.

Thanks Ziya.

Morgan

LazZiya commented 3 years ago

Don't worry, all of us does such mistakes :)

Just for clarification, you can localize any attribute by adding localize-att- prefix as below:

localize-att-title="..."
localize-att-alt="..."
localize-att-src="..."
localize-att-data-whatever="..."

Kind regards, Ziya

morgrowe commented 3 years ago

Oh right, I didn't realise. That's great. Looks like I won't need the IStringLocalizer after all.

Thanks again, Morgan