[WIP] Templating changes

| Q             | A
| ------------- | ---
| Bug fix?      | yes
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #11748
| License       | MIT
| Doc PR        | n/a

This is an attempt to fix #11748 and at the same time, trying to decouple things and prepare 3.0 where the PHP templating engine will probably be moved outside the core framework.

THIS IS WORK IN PROGRESS AND THIS IS NOT FINISHED YET.