0

I have field names:

  • field_en_image
  • field_sv_image

node_lang is set as a variable in the .theme file under _preprocess_node hook.

I want to print the field dynamically in the twig template file based on the current language.

{{ node.["field_"~node_lang~"image"]|view }}

but this seems to be not working.

2
  • 1
    I think this is a general Twig question and as such off-topic. What you're looking for are dynamic variable names in Twig
    – Hudri
    Oct 18, 2019 at 7:33
  • {% set fieldName = "field_" ~ node_lang ~ "_title" %} {{ fieldName.value }} {{ fieldName.view }} is not working as well
    – DrupBha
    Oct 21, 2019 at 8:13

2 Answers 2

1

Try the following

{% set field_name = "field_"~node_lang~"image" %}
{{ attribute(node,field_name) | view }} 

or

{% set field_name = "field_"~node_lang~"image" %}
{{ attribute(content,field_name) }} 

If you want to access a dynamic attribute of a variable, use the attribute function instead.

The attribute function is also useful when the attribute contains special characters (like - that would be interpreted as the minus operator):

{# equivalent to the non-working foo.data-foo #}
{{ attribute(foo, 'data-foo') }}
0

You should be using the _context variable instead, which represent the whole accessibles variables, you can find some informations about that variable under Macros documentation.

That snippet may help :

{% set language = 'fr' %}

{% set foobar = _context["field_" ~ language ~ "_foobar"] is defined ? _context["field_" ~ language ~ "_foobar"] : null %}

{{ foobar }}

I've wrote to you a little TwigFiddle, check it out :)

2
  • I tried below, but its not displaying anything. {% set language = 'fi' %} {% set foobar = context["field" ~ language ~ "title"] is defined ? _context["field" ~ language ~ "_title"] : null %} {{ foobar }}
    – DrupBha
    Oct 21, 2019 at 8:10
  • Those fields field_fi_title and every "languages related" ones exists in the database ?
    – Tarto
    Dec 2, 2019 at 13:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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