What is the standard method for adding classes in twig template?
I'm going straightly to the main subject point:

I have some classes and I want to collect them in a group and add this group to the existing group that added before:
I try below code but it seems that something is wrong.

  set classes = [
    'block-' ~ configuration.provider|clean_class,
    'block-' ~ plugin_id|clean_class,

  set my-classes = [
<div{{ attributes.addClass('classes my-classes') }}>

What tips should I consider for a class group name, For example, Is it important to follow PHP variables name convention, Can I use hyphen character in class group names?

Scenario -2:
I have few classes names and I want to add theme straightly to default added classes, like below:


<div {{ row.attributes.addClass(row_classes 'class-name-1 class-name-2') }}>

Your variables classesand my_classes are arrays. You could merge them:

{{ attributes.addClass(classes, my_classes) }}

Or add them one by one:

{{ attributes.addClass(classes).addClass(my_classes) }}

Or merge an array constant directly:

{{ row.attributes.addClass(row_classes, ['class-name-1', 'class-name-2']) }}

Or single classes:

{{ row.attributes.addClass(row_classes, 'class-name-1', 'class-name-2') }}

According to the coding standards https://twig.symfony.com/doc/2.x/coding_standards.html you should use underscores in variable names.

| improve this answer | |
  • Thank you so much, for your help and reply. I appreciate you greatly. – Mojtaba Reyhani Jul 28 '17 at 1:36

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.