0

I am using Paragraphs module to create a cutom paragraph. The custom paragraph will have three fields: Image, Text and Position. Would like to use css to align as follows based on the value of the Position field.

Image Left | Text Right

Text Left | Image Right

Image Top / Text Below

How do I go about doing this? Do I need any extra configuration for the paragraph? Or is all the magic done in CSS?

1
  • 1
    Doing it based on a field is fine, alternatively you can also use the styles feature that we're working on in drupal.org/project/paragraphs_collection, then you can just define styles and style groups in a yml file with corresponding classes and enable the groups on the paragraph types you want to have this.
    – Berdir
    Sep 2, 2018 at 14:45

1 Answer 1

4

Yes, just CSS. You could use Classy Paragraphs to append CSS classes to your paragraphs depending on some field values, or you can do this very easily yourself (recommended) by preprocessing the paragraph in your theme's *.theme file.


Let's assume the position field is a single-value List (Text) field with the following allowed values:

image-left|image-left
image-right|image-right
image-top|image-top

Then you can easily retrieve that value and append it as CSS class by implementing hook_preprocess_HOOK:

/**
 * Implements template_preprocess_paragraph().
 */
function MYTHEME_preprocess_paragraph(&$variables) {

  $paragraph = $variables['paragraph'];

  // Retrieve certain field's values and add them as CSS classes.
  $classy_fields = [
    'field_image_position',
    'field_background_color',
    'field_social_media_type',
  ];

  foreach ($classy_fields as $classy_field) {

    if ($paragraph->hasField($classy_field)) {

      if (!$paragraph->get($classy_field)->isEmpty()) {

        $variables['attributes']['class'][] = $paragraph->get($classy_field)->getString();
      } 
    }
  }
}

Which will result in image-right or whatever other class getting appended to this paragraph's attributes and it now can by styled accordingly:

<div class="paragraph-MYPARAGRAPH view-mode--default image-right">

Your Answer

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

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