fluid icon indicating copy to clipboard operation
fluid copied to clipboard

Add translate filter and supporting infrastructure.

Open zxjon22 opened this issue 3 years ago • 4 comments

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 (or t) filter to load and use translations from an external source.
  • Adds an IResourcesProvider to TemplateContext and TemplateOptions for the filter to load translations.
  • Adds a concrete ResxResourcesProvider to 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>

zxjon22 avatar Jun 29 '22 16:06 zxjon22

Interested, I need to have a look to this one ASAP

hishamco avatar Jun 30 '22 16:06 hishamco

At the first glance I'm not sure if @sebastienros agree to use RESX for localization string

hishamco avatar Jun 30 '22 16:06 hishamco

I think this matter should be given to the theme engine to do it, not a template engine.

Soar360 avatar Jul 01 '22 05:07 Soar360

IMHO this filter might go into OC

hishamco avatar Jul 01 '22 09:07 hishamco

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

sebastienros avatar Sep 21 '22 17:09 sebastienros

But I might change my mind later on. I see you haven't added any external dependencies which I like.

sebastienros avatar Sep 21 '22 17:09 sebastienros