apostrophe icon indicating copy to clipboard operation
apostrophe copied to clipboard

Make __t() globally available per request

Open myovchev opened this issue 2 years ago • 3 comments

Summary

This patch adds the __t() as global helper so that it is available for macros too. This is possible because getEnv() handler receives a real request object when called by our parsers on request. This should be 100% backward compatible change - the fragments are using custom context which takes precedence over the global context.

What are the specific steps to test this change?

Use {{ __t('Some phrase') }} inside a macro. It should render properly (with no parse errors).

What kind of change does this PR introduce?

(Check at least one)

  • [x] Bug fix
  • [ ] New feature
  • [ ] Refactor
  • [ ] Documentation
  • [ ] Build-related changes
  • [ ] Other

Make sure the PR fulfills these requirements:

  • [x] It includes a) the existing issue ID being resolved, b) a convincing reason for adding this feature, or c) a clear description of the bug it resolves
  • [x] The changelog is updated
  • [ ] Related documentation has been updated
  • [x] Related tests have been updated

myovchev avatar Jun 23 '22 12:06 myovchev

@boutell The proposed solution won't work because the context does not have __req (possibly it would have if called with with context but this also fails when multiple cross imports are made).

A second attempt - we don't mess up with the getEnv, instead we use renderBody as the point to introduce global context, which should be propagated down to any registered macros and custom tags not extending Apostrophe.

myovchev avatar Jun 24 '22 11:06 myovchev

This works out to the same thing as the original attempt. There is one global in an env object that may be in the middle of several overlapping asynchronous render calls.

Since per-request environments have a huge performance cost, and context doesn't make it through without with context and in the situations you mention, I think the proper answer is to deprecate macros more thoroughly. They are not async friendly. Fragments are the async-friendly, widget-friendly, Apostrophe-friendly replacement for macros.

boutell avatar Jun 27 '22 13:06 boutell

Actually, I thought of another way 😆

Right now we have one env per module.

We can break it down more and have one env per module plus locale name.

Then there should be no problem with the addGlobal call because req.__t will always be a req with the same locale.

boutell avatar Jun 27 '22 13:06 boutell

Closing as stale. Note my above comments on how it could be reworked if desired.

boutell avatar Jan 23 '23 18:01 boutell