fluid
fluid copied to clipboard
Add translate filter and supporting infrastructure.
Hi there, I had a requirement for something like See https://shopify.dev/themes/architecture/locales/storefront-locale-files to use translations from resx files.
Not sure if it's something you'd like in the base library but here's a PR for it.
- Adds a
translate(ort) filter to load and use translations from an external source. - Adds an
IResourcesProvidertoTemplateContextandTemplateOptionsfor the filter to load translations. - Adds a concrete
ResxResourcesProviderto load translations from standard .NET resx files.
There is also a NullResourcesProvider which simply returns the translation key unmodified - this is installed by default. I'm not 100% sure about this. I added it so that using t wouldn't cause a crash if a suitable IResourcesProvider wasnt configured but maybe it's better to throw an exception.
Use it like this:
var rp = new ResxResourcesProvider("MyApp.Resources", GetType().Assembly);
var context = new TemplateContext { ResourcesProvider = rp } ;
var result = template.Render(context);
<?xml version="1.0" encoding="utf-8"?>
<!-- MyApp.Resources.resx -->
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
</xsd:schema>
<data name="Welcome" xml:space="preserve">
<value>Hello there!</value>
</data>
<data name="Footer" xml:space="preserve">
<value>Goodbye, {0}.</value>
</data>
</root>
<p>{{ "Welcome" | t }}</p>
<p>{{ "Goodbye" | t: "Bob"}}</p>
Result
<p>Hello there!</p>
<p>Goodbye Bob.</p>
Interested, I need to have a look to this one ASAP
At the first glance I'm not sure if @sebastienros agree to use RESX for localization string
I think this matter should be given to the theme engine to do it, not a template engine.
IMHO this filter might go into OC
I like what you are doing here but I don't think it should be part of the engine natively. I suggest you keep it in your source code or create a separate package that adds this support to Fluid.
For instance here is how we did it in Orchard Core, by using the ASP.NET ViewLocalizer https://github.com/OrchardCMS/OrchardCore/blob/main/src/OrchardCore/OrchardCore.DisplayManagement.Liquid/Filters/LiquidViewFilters.cs#L13
But I might change my mind later on. I see you haven't added any external dependencies which I like.