Orchardcore localization source

From CrestApps/CrestApps.AgentSkills · View interactive version

Orchardcore localization source is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for deferred localization with LocalizationSource in Orchard Core 4.0. Covers Create(value, type), Create of T, translator notes, the IStringLocalizerFactory and IHtmlLocalizerFactory Localize and Plural extensions with Arg names, why deferred sources exist, CommonLocalizationSources and per-m

How to use this skill

Skill file

Orchard Core Deferred Localization with LocalizationSource - Prompt Templates

Declare Now, Translate at Display Time

You are an Orchard Core expert. Generate code that declares translatable text where no localizer or culture is available and translates it when it is shown.

Guidelines

Why Deferred Sources Exist

Declaring and Translating

using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.Extensions.Localization;
using OrchardCore.Localization;

namespace MyModule.Services;

public static class OrderMessages
{
    // Static classes cannot be generic arguments, so use typeof().
    public static readonly LocalizationSource Shipped =
        LocalizationSource.Create("Order {0} was shipped to {1}.", typeof(OrderMessages));

    public static readonly LocalizationSource Banner =
        LocalizationSource.Create("<strong>Free shipping</strong> on orders over {0}", typeof(OrderMessages));
}

public sealed class OrderNotifier
{
    private static readonly LocalizationSource s_pendingItems =
        LocalizationSource.Create<OrderNotifier>("{0} item is waiting in order {1}");

    private readonly IStringLocalizerFactory _stringLocalizerFactory;
    private readonly IHtmlLocalizerFactory _htmlLocalizerFactory;

    public OrderNotifier(
        IStringLocalizerFactory stringLocalizerFactory,
        IHtmlLocalizerFactory htmlLocalizerFactory)
    {
        _stringLocalizerFactory = stringLocalizerFactory;
        _htmlLocalizerFactory = htmlLocalizerFactory;
    }

    public LocalizedString ShippedText(string orderNumber, string city)
        => _stringLocalizerFactory.Localize(OrderMessages.Shipped, orderNumber, city);

    public LocalizedHtmlString BannerHtml(decimal threshold)
        => _htmlLocalizerFactory.Localize(OrderMessages.Banner, threshold.ToString("C"));

    public LocalizedString PendingItems(int count, string orderNumber)
        => _stringLocalizerFactory.Plural(count, s_pendingItems, "{0} items are waiting in order {1}", orderNumber);
}

| Extension | Namespace and package | Returns |

|---|---|---|

| IStringLocalizerFactory.Localize(source, params object[] arguments) | Microsoft.Extensions.Localization, OrchardCore.Abstractions | LocalizedString |

| IHtmlLocalizerFactory.Localize(source, params object[] arguments) | Microsoft.AspNetCore.Mvc.Localization, OrchardCore.Abstractions | LocalizedHtmlString |

| IStringLocalizerFactory.Plural(count, source, plural, params object[] arguments) | Microsoft.Extensions.Localization, OrchardCore.Localization.Abstractions | LocalizedString |

| IHtmlLocalizerFactory.Plural(count, source, plural, params object[] arguments) | Microsoft.AspNetCore.Mvc.Localization, OrchardCore.Localization.Abstractions | LocalizedHtmlString |

Behavior:

PO File Entries

For the sources above (MyModule.Services namespace):

msgctxt "MyModule.Services.OrderMessages"
msgid "Order {0} was shipped to {1}."
msgstr "La commande {0} a été expédiée à {1}."

msgctxt "MyModule.Services.OrderNotifier"
msgid "{0} item is waiting in order {1}"
msgid_plural "{0} items are waiting in order {1}"
msgstr[0] "{0} article attend dans la commande {1}"
msgstr[1] "{0} articles attendent dans la commande {1}"

The singular Value is the msgid; the plural argument is the msgid_plural. PO file locations are covered by orchardcore-localization.

Displaying in Razor

@using Microsoft.Extensions.Localization
@inject IStringLocalizerFactory StringLocalizerFactory

<span class="badge text-bg-secondary">@StringLocalizerFactory.Localize(Model.Step.Category)</span>
<strong>@(StringLocalizerFactory.Localize(Model.Step.Title)?.Value ?? Model.Step.Name)</strong>

Sharing Sources

A source is immutable and culture-independent, so declare it once and reuse it wherever the text has the same meaning; it is then translated with a single PO entry.

using OrchardCore.Localization;

namespace MyModule;

internal static class MyModuleLocalizationSources
{
    public static readonly LocalizationSource ExportMyData = LocalizationSource.Create("Export My Data", typeof(MyModuleLocalizationSources));
}
msgctxt "OrchardCore.Localization.CommonLocalizationSources"
msgid "Content Management"
msgstr "Gestion du contenu"

msgctxt "MyModule.MyModuleLocalizationSources"
msgid "Export My Data"
msgstr "Exporter mes données"

Translator Notes and Argument Names

A source takes a note for translators where it is declared; the note is written to the translation template as a #. comment, is not stored in the source, and does not change its value or equality. Name format arguments with Arg(name, value) (static OrchardCore.Localization.LocalizationMetadata, returns its value unchanged) where the source is formatted. Arg(name, count, min, max) also declares the range of a plural count, written as the gettext range flag.

using Microsoft.Extensions.Localization;
using OrchardCore.Localization;
using static OrchardCore.Localization.LocalizationMetadata;

public static class DashboardMessages
{
    public static readonly LocalizationSource Greeting = LocalizationSource.Create(
        "Hello {0}",
        typeof(DashboardMessages),
        note: "Greeting shown on the dashboard.");

    public static readonly LocalizationSource DayLeft =
        LocalizationSource.Create("{0} day left", typeof(DashboardMessages));
}

// At display time:
var text = stringLocalizerFactory.Localize(DashboardMessages.Greeting, Arg("user name", user.Name));
var days = stringLocalizerFactory.Plural(Arg("days", count, 1, 7), DashboardMessages.DayLeft, "{0} days left");

The overloads are Create(value, type, note), Create<T>(value, note) and the matching constructor LocalizationSource(value, type, note). Notes, names and range bounds must be compile-time constants to be extracted.

Analyzer Rules

OrchardCore.Abstractions ships Roslyn analyzers, with a code fix, for every project referencing it:

| Rule | Severity | Reported when |

|---|---|---|

| OCLOC101 | Warning | A constant value has no context, for example LocalizationSource.Create("Manage widgets"). The code fix adds the containing type (Create<T>, or typeof(T) for a static class). |

| OCLOC102 | Info | The context is not the declaring type or one of its containing types. Fine when strings deliberately share a context. |

| OCLOC103 | Warning | The value is not a compile-time constant, so it cannot be extracted. |

| OCLOC104 | Warning | A localizer indexer, GetString, GetHtml or Plural key is not a compile-time constant. |

Members and types marked [SkipLocalizationExtraction] (namespace OrchardCore.Localization) are not analyzed or extracted; reserve it for helpers that forward keys declared elsewhere. Suppress a rule around an intentionally dynamic call with #pragma warning disable OCLOC104 and a comment saying where the keys come from, or set its severity in .editorconfig (dotnet_diagnostic.OCLOC102.severity = none). A context-free source whose value is not a constant is not reported, since it forwards a value declared elsewhere.

Where Orchard Core 4.0 Uses LocalizationSource

| API | Declared as | Translated by |

|---|---|---|

| Permission.Description | Constructor argument; built-in permissions use LocalizationSource.Create(description, typeof(DeclaringType)) | Roles editor, admin menu link and placeholder node permission pickers, menu item permission picker |

| DeploymentStep.Category, DeploymentStep.Title | Read-only virtual properties overridden to return shared sources (CommonLocalizationSources or the module's *LocalizationSources class); [JsonIgnore] on each override, never persisted | Deployment plan page (step picker groups) and the step add and edit screens |

| PermissionTemplate.Description | A source with {0}, formatted into a context-free description by CreateDynamicPermission(...) | Roles editor (through Data Localization) |

| IDataSource.DisplayName, Description (and DataSourceDescriptor) | static abstract interface properties, for example public static LocalizationSource DisplayName { get; } = LocalizationSource.Create<MyDataSource>("Orders"); | Data source pickers |

| IDataFileFormat.DisplayName (and DataFileFormatDescriptor) | Same pattern | File format pickers |

| IDataPipelineStepType.DisplayName, Description (and DataPipelineStepTypeDescriptor) | Same pattern | Data Pipelines designer and run views |

| ISharedLinkHandler.DisplayName (and SharedLinkHandlerDescriptor) | Same pattern | Shared download links admin |

See orchardcore-permission-providers, orchardcore-deployments, orchardcore-data-sources, orchardcore-data-pipeline-steps and orchardcore-data-pipelines for the rest of those APIs.

Permission Descriptions

using OrchardCore.Localization;
using OrchardCore.Security.Permissions;

namespace MyModule;

public static class WidgetPermissions
{
    public static readonly Permission ManageWidgets = new(
        "ManageWidgets",
        LocalizationSource.Create("Manage widgets", typeof(WidgetPermissions)),
        isSecurityCritical: true);
}
msgctxt "MyModule.WidgetPermissions"
msgid "Manage widgets"
msgstr "Gérer les widgets"

Deployment Step Labels

using System.Text.Json.Serialization;
using OrchardCore.Deployment;
using OrchardCore.Localization;

namespace MyModule.Deployment;

public sealed class WidgetsDeploymentStep : DeploymentStep
{
    public override string Name => "Widgets";

    // [JsonIgnore] is not inherited by overrides, and a LocalizationSource must never be serialized.
    [JsonIgnore]
    public override LocalizationSource Category => CommonLocalizationSources.Content;

    [JsonIgnore]
    public override LocalizationSource Title => MyModuleLocalizationSources.Widgets;
}

MyModuleLocalizationSources.Widgets is declared like ExportMyData in Sharing Sources above.

The category is translated with msgctxt "OrchardCore.Localization.CommonLocalizationSources" and the title with msgctxt "MyModule.MyModuleLocalizationSources". Translations keyed by the old step-type context (MyModule.Deployment.WidgetsDeploymentStep) must be moved to the new contexts.

Data Localization Interaction

Upgrading from 3.x

Troubleshooting

| Symptom | Check |

|---|---|

| A permission description stays in English with a PO entry | The source has no Type, or msgctxt does not equal the type's full name. |

| A permission translation from Data Localization stopped working | The built-in description now has a Type; translate it with a PO file. |

| Placeholders appear unformatted | Pass the arguments to Localize()/Plural(), not to Create(). |

| A deployment plan or other saved document holds label text such as "Content", or a label read back is untranslated | A LocalizationSource property (for example a Category or Title override) lacks [JsonIgnore]. System.Text.Json writes a source as its Value and reads it back without its Type, so it is never translated with its PO context. Add [JsonIgnore] to every LocalizationSource property. |

| A deployment step category or title lost its translation after upgrading | Its PO entry still uses the step-type msgctxt; use OrchardCore.Localization.CommonLocalizationSources or the module's *LocalizationSources class. |

| OCLOC101 on a declaration | Add the context: Create<T>(value) or Create(value, typeof(T)). |

| Plural form is wrong in a language with several forms | The source has no Type, so the English rule applied. |

| HTML tags appear escaped | Use IHtmlLocalizerFactory.Localize() for trusted markup. |

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.