3

Is there any difference between writing CSS classes directly to Html tags and using the Attribute class?

Is there any difference between attributes, title_attributes, and content_attributes? What is the usage of each of them?

I read Using attributes in templates, but it doesn't explain that clearly.

1 Answer 1

5

This depends on the template you use. If you use for example the node template

node.html.twig

<article{{ attributes }}>

  {{ title_prefix }}
  {% if not page %}
    <h2{{ title_attributes }}>
      <a href="{{ url }}" rel="bookmark">{{ label }}</a>
    </h2>
  {% endif %}
  {{ title_suffix }}

  {% if display_submitted %}
    <footer>
      {{ author_picture }}
      <div{{ author_attributes }}>
        {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}
        {{ metadata }}
      </div>
    </footer>
  {% endif %}

  <div{{ content_attributes }}>
    {{ content }}
  </div>

</article>

You have four attributes variables

  1. attributes
  2. title_attributes
  3. author_attributes
  4. content_attributes

The difference between them is that they have different targets in the html markup of the template. The main attributes variable in a node is for the <article> tag, in a form for the <form> tag or in other templates often a simple wrapper <div>. If a template defines additional attributes variables they are for that specific part of the template, in a node for the title, author and content.

Always add attributes to the existing variable like explained in the linked documentation. Never replace it with your own attributes, because a lot of code depends on that the template is actually using the attributes variables.

2
  • Thank you so much for your help and reply, If I'm not mistaken the attributes add default and general attributes that added by Drupal UI like views to tag and .addClass(classes) add extra Special Classes to it, Is it true? Please explain a little more. Commented Feb 23, 2017 at 12:12
  • 2
    Views is only one example, every code component,is it from core, contrib or custom, a module (core has also modules), a theme or the drupal core itself can add attributes down the pipeline of the different stages of the build and rendering process. And they often do this in certain circumstances you might not be aware of when you design the template.
    – 4uk4
    Commented Feb 23, 2017 at 12:20

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.