A quick addition/clarification:
-
Regarding field overriding for the Admin Panel: if you override an existing core field (i.e., same name, same
type, e.g.,display), instead of creating a new one (e.g.,display_complex_trans), you must use a different approach:- The path must be registered using the
onAdminTwigTemplatePathsfunction in your theme/plugin (see docs for Extending the Admin Themes). - The standard path:
user/themes/YOURTHEME/admin/themes/grav/templates/forms/fields/field_name/field_name.html.twig #the path refers to the admin plugin's internal structure
- The path must be registered using the
-
I also fell into a rabbit hole
while testing my custom form field. The Twig macro I shared works perfectly in the admin but exhibits incorrect behavior in a frontend form. It seems that translation processing is handled differently in the two contexts.
The most stable solution I have achieved so far, which now works reliably in both cases, is shown below. But I think a more elegant solution could be found.
Updated Twig Macro Example
Current working macro (Max 5 arguments)
{# Macro #}
{% macro complex_translation(attribute='', translation_vars=[], markdown=false ) %}
{% set field_attribute = markdown ? attribute|markdown(false) : attribute %}
{% set args = [] %}
{% for value in translation_vars %}
{% set args = args|merge([ value|t ]) %}
{% endfor %}
{% set count = args|length %}
{% if count <= 5 %}
{% switch count %}
{% case 1 %}
{% set field_attribute = field_attribute|t(args[0]) %}
{% case 2 %}
{% set field_attribute = field_attribute|t(args[0], args[1]) %}
{% case 3 %}
{% set field_attribute = field_attribute|t(args[0], args[1], args[2]) %}
{% case 4 %}
{% set field_attribute = field_attribute|t(args[0], args[1], args[2], args[3]) %}
{% case 5 %}
{% set field_attribute = field_attribute|t(args[0], args[1], args[2], args[3], args[4]) %}
{% default %}
{% set field_attribute = field_attribute|t %}
{% endswitch %}
{{ field_attribute|e }}
{% else %}
{% set error_msg = 'Error: The complex_translation macro received ' ~ count ~ ' variables, but supports a maximum of 5.' %}
<div class="notices red"><p>{{ error_msg|raw }}</p></div>
{% endif %}
{% endmacro %}