htmlcssaemsightlyhtl

Run time variable is not resolved inside style element in Sightly in AEM 6.2


I am trying to provide the background image to a div by creating a variable in sightly.

I am reading a property with sightly and when I supply this to style tag, it does not work.

here is the html

<sly data-sly-test.fileReference="${properties.title}" />

<div style="background: url(${fileReference}); background-position: center top;">
<p>${properties.title}</p>

When the page is rendered this is what I see

<div style="background: url(); background-position: center top;">
<p>my Title</p></div>

It means that ${properties.title} inside the <p> tag is accepted but it does not work with inside style element.


Solution

  • The variable is resolved just fine. The reason your url() value is empty is because you're not using the right Display Context. Also, the value, you're passing there, the string "my Title", is not a valid URL (what you need to print) or a valid style token (what usually gets rendered in a style attribute)

    You'll notice that each of the following expressions renders an empty url() value:

    <div style="background: url(${'cookies'});"></div>
    <div style="background: url(${'cookies with chocolate chips'});"></div>
    
    <!--/* both print background: url();*/-->
    

    If we force the display context to allow any string, the value will be printed

    <div style="background: url(${'cookies' @ context='unsafe'});">
    </div>
    <!--/* prints background: url(cookies);*/-->
    

    In script and style contexts, HTL requires the display context to be stated explicitly. If it's not, the output is not rendered.

    What you want to output to show a background image is the URL of an image. Let's try making this explicit:

    <div style="background: url('${'/etc/designs/myapp/img/someimage.png' @ context='uri'}');">
    </div>
    <!--/* prints background: url('/etc/designs/myapp/img/someimage.png');*/-->
    

    There, that does the trick!

    Now, as a word of advice, try to avoid inline styling. You'll save yourself similar problems with display contexts and your CSS will be easier to maintain if it's part of a client library.