How to set background Image in aem component, using sightly

Viewed 1001

I am using the below code for setting responsive background Image dynamically, but it's not working in my component. Image is not showing and my UI is also disturbed.

Please suggest the right code for my component to add a background image dynamically.

<sly data-sly-set.backgroundImage="--backgroundImage:url('${model.backgroundImg}');"
         data-sly-set.backgroundImageSmall="--backgroundImageSmall:url('${model.backgroundImgSmall}');"
         data-sly-set.backgroundColor="background-color: ${model.backgroundColor}"
         data-sly-set.backgroundImageStyle="${model.backgroundImg ? backgroundImage : '' };${model.backgroundImgSmall ? backgroundImageSmall : '' };${properties.backgroundLayout};${model.backgroundColor ? backgroundColor : '' }"></sly>
         <div class="superteaser-grid ${model.gridStyle}" style="--backgroundImage:${backgroundImageStyle @ context='unsafe'}; "> 
      
1 Answers

The code you pasted does not make much sense:

<sly data-sly-set.backgroundImage="--backgroundImage:url('${model.backgroundImg}');"
         data-sly-set.backgroundImageSmall="--backgroundImageSmall:url('${model.backgroundImgSmall}');"
         data-sly-set.backgroundColor="background-color: ${model.backgroundColor}"
         data-sly-set.backgroundImageStyle="${model.backgroundImg ? backgroundImage : '' };${model.backgroundImgSmall ? backgroundImageSmall : '' };${properties.backgroundLayout};${model.backgroundColor ? backgroundColor : '' }"></sly>
         <div class="superteaser-grid ${model.gridStyle}" style="--backgroundImage:${backgroundImageStyle @ context='unsafe'}; ">

as --backGroundImage is not a legitimate CSS property. It does however look like a BEM modifier so maybe you want to use it like that:

<sly data-sly-set.backgroundModifier="${model.backgroundImg ? '--backgroundImage' : (model.backgroundImgSmall ? '-backgroundImageSmall' : '')}"
     data-sly-set.backgroundStyle="url(${model.backgroundImg || model.backgroundImgSmall}) ${properties.backgroundLayout} ${model.backgroundColor ? backgroundColor : '' }">
    <div class="superteaser-grid${backgroundModifier}" style="background:${backgroundStyle @ context='unsafe'}"></div>
</sly>

Of course, you can improve this to conditionally add url() and spacing in backgroundStyle but I wanted to keep the example as small as possible.

Related