1

For the basic page content type I added a custom boolean field called field_login_required.

In my node template node--page.html.twig I have

    <h2>{{ title }}</h2>
    {% if content.field_login_required %}
        {% if user == 0 %}
        <p class="must-login">You must be logged in to view this page <a href="/user">Please click here to login</a></p>
        {% else %}
            <p>{{ content.body }}</p>
        {% endif %}
    {% else %}
        <p>{{ content.body }}</p>
    {% endif %}

However content.field_login_required is null no matter whether the checkbox is checked or not. To test what was available I used

{{ dump(content|keys) }}

However the result of this is

array (size=1)
  0 => string 'body' (length=4)

field_login_required is omitted. Is there anyway to refer to a custom field in a node template?

1

The issue occurred because

{{ content.field_login_required }} 

was used. Node should be used in place of content. The proper code is

{{ node.field_login_required.value }}
  • 1
    that's not correct because the field object will always exist. if you want to check if the checkbox is checked or not, use node.custom_field.value – Berdir Sep 14 '16 at 19:18
  • You are correct I'm updating the answer to reflect this – Matt Sep 14 '16 at 19:28

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.