0

does Twig provide any way to translate string which is passed to macro? I thought that it would work in similar way to Wordpress translation function where instead of string I just provide the variable. But it does not work.

Here is my macro:

{% macro input(type, name, placeholder, value, class) %}
<input type="{{ type|default('text') }}" name="{{ name }}" placeholder="{{ placeholder | t}}" value="{{ value | e }}"
       class="{{ class }}">
{% endmacro %}

Then I call it in this way:

{{ macro.input('text', 'name', 'Name...') }}

I want just to translate the placeholders but when I use | t filter drupal returns the error:

InvalidArgumentException: $string ("") must be a string. in Drupal\Core\StringTranslation\TranslatableMarkup->__construct() (line 140 of F:\xampp\htdocs\va\core\lib\Drupal\Core\StringTranslation\TranslatableMarkup.php).

I am aware that input is not great example and I should use form API, it's just the easiest to explain. Is there any way of translating strings which are passed to macros?

1

I found the solution. The |filter has to be included while calling macro like this:

{{ macro.input('text', 'name', 'Name...' | t) }}
  • Maybe there might be a way to make it work inside the macro, but this is the recommended approach anyway. t should, if at all possible, always be called on the actual string, not on a variable. That allows tolls like potx (which localize.drupal.org uses for example) to extract translatable strings from the files. While localize.drupal.org is only for core/contrib, you might also end up using that tool to create translation files to translate your module for custom code. – Berdir Aug 1 '16 at 20:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.