Newby here.
I was trying to find an example where I can integrate multi-language through:
Microsoft.AspNetCore.Mvc.Localization
So I can use for example .Title instead of creating if statement for .Title.de or .Title.en.
The same way you do it with AppResource.
Is there an easy way to implement proper localization integration?
Best,
F.
In step 1 you have to setup ASP.NET Localization. Then you will have the current language code globally available as CultureInfo.CurrentUICulture.ToString().
public sealed class LocalizedValue<T> : Dictionary<string, T>
{
public T Value
{
get
{
var language = CultureInfo.CurrentUICulture.ToString();
// Get value current request language.
if (this.TryGetValue(language, out var value))
{
return value;
}
// Get value by master language.
if (this.TryGetValue("master", out value))
{
return value;
}
return default;
}
}
}
You can also implement ToString() and an implicit conversion operator.
Then you define your model like this:
public sealed class BlogPostData
{
// For localizable fields you can use dictionaries.
public LocalizedValue<string> Title { get; set; }
}
public sealed class BlogPost : Content<BlogPostData>
{
}
The advantage is that if you want to cache requests, you only have to cache them once.
2. Decide about language in Client
You have to pass the language to Squidex via the X-Languages and X-Flatten header.
var language = CultureInfo.CurrentUICulture.ToString();
var context =
QueryContext.Default
.WithFlatten()
.WithLanguages(language);
var content = await contents.GetAsync(id, contex);
Then you can configure your mode llike this:
public sealed class BlogPostData
{
// This is in the global request.
public string Title { get; set; }
}
public sealed class BlogPost : Content<BlogPostData>
{
}
In all requests
If you want to add headers for all requests you can do that. It follows the principles described here:
The options object has a new property called ClientFactory now. This is an example implementation.
You can also write such a factory that adds the language headers to each request based on the current culture.