1

For form fields, we have label and field (Text/Select/...).

How do I get the field title and its value separately in a template file?

{{ form.title }}

I need both separately, so I can properly style.

3
  • label form.title['#title'] value form.title.0 Note: this will only get the first value, if it's a multi-value field you need to loop.
    – No Sssweat
    Nov 7, 2017 at 10:49
  • Thanks @NoSssweat In this way will get title. But how to get field separately as well
    – Mike
    Nov 8, 2017 at 2:14
  • did you try form.title.0 ?
    – No Sssweat
    Nov 8, 2017 at 11:16

1 Answer 1

2

To access separately labels and values for fields in twig template (example in node twig template: node.html.twig) I propose to loop all the node variable.

My example: Instead of print all content with this line {{ content }} loop the content object

    {% for item in node %}
        {# Print the label of the field #}
        {{ item.fieldDefinition.label }}

        {# Print the value of a field text/simple field #}
        {{ item.fieldDefinition.value }}

        {# Print the value of a field reference  #}
        {{ item.value[0]['target_id'] }}
    {% endfor %}

Other way is to use this module: https://www.drupal.org/project/twig_field_value

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.