Conditional classes for each slice in SliceZone

Previously I used my own slice machine where I conditionally rendered padding classes based on the previous slice’s background colour or if it had a title. It worked quite well and I could have quite dynamic slices but still have consistent spacing.

Clients would ask if they could not have titles on certain spaces (so slices could be visually combined for the visitors).

index.vue on slice loop:

      :class="[
        prismicLast(slice, index, document.data.body),
        'slice-container',
        sliceClass(slice)
      ]"

Slices.js as mixin:

    prismicLast(item, index, data) {
      if (index > 0) {
        let currentHexColor = 0
        const previousHexColor = data[index - 1].primary.background_color
        currentHexColor = data[index].primary.background_color
        if (previousHexColor === currentHexColor) {
          if (
            data[index].primary.heading[0] === undefined ||
            data[index].primary.heading.length == 0 ||
            data[index].primary.heading[0].text.length === 0
          ) {
            return 'heading-false samecolor py-16'
          } else {
            return 'heading samecolor pb-16'
          }
        } else {
          if (
            data[index].primary.heading[0] === undefined ||
            data[index].primary.heading.length == 0 ||
            data[index].primary.heading[0].text.length === 0
          ) {
            return 'notsamecolor heading-false py-16'
          } else {
            return 'notsamecolor heading pb-16'
          }
        }
      } else {
        // if index is > 0
        if (index === 0) {
          if (
            data[0].primary.heading === undefined ||
            data[0].primary.heading.length == 0 ||
            data[0].primary.heading[0].text.length === 0
          ) {
            return 'firstItem heading-false py-16'
          }
          return 'firstItem heading py-16'
        }
      }
      return false
    },

I don’t think I could do this at component level because I need to check the options in the previous slice. cc/ @hugo.villain

Spacing between slices and titles is an interesting problem to solve. Can you please provide illustrations or some kind of quick sketches to show the different problems that you would get if we don’t address the problem @jjames.home ? :pray:

I think you could achieve this by using a function as theme, by checking the position of the slice and returning a class attribute. I’ll add a len property here to make things easier for you.

Adding a padding prop to the theme would also be super helpful here, to be passed to the section wrapper of each slice.

1 Like