Search code examples
compiler-errorslessquotesword-wrap

LESS, compile issues with variables inside CSS urls


I've created a small LESS based mixin for outputting images in either standard or retina format. I can't get my head around wrapping variables inside some of the CSS urls that goes along with this - when I compile the code below I end up with url('http://sample.com/images/'[email protected]''). Both background properties seem to need to be wrapped inside quotes in order for the compiler to fetch the variables. While this works, as I try and set the background property for the high ppi scenario I end up with these extra single quotes around the filename.

.image(@path, @w: auto, @h: auto) {
    background-image: url('@{base-url}/images/@{path}');
    @path_2x: ~`"@{path}".split('.').slice(0, "@{path}".split('.').length - 1).join(".") + "@2x" + "." + "@{path}".split('.')["@{path}".split('.').length - 1]`;

    @media all and (-webkit-min-device-pixel-ratio : 1.5) {
        background-image: url('@{base-url}/images/@{path_2x}');
        background-size: @w @h;
    }
}

Any ideas?


Solution

  • I'm assuming you are passing the @path as a string itself, something like:

    .image('sprite.png');
    

    You can do one of two things:

    1) Escape it at time of call (less user friendly)

    .image(~'sprite.png');
    

    2) Modify the javascript to not add the extra quotes (user friendly)

    This keeps the unescaped call .image('sprite.png');, but notice here I have changed your "@{path}" to just @{path} since the path is already being passed as a string, so @{path} already resolves to a string and is capable of string operations. By adding the quotes, you are essentially making the path from 'sprite.png' to "'sprite.png'" which is then leaving the extra quotes.

    @path_2x: ~`@{path}.split('.').slice(0, "@{path}".split('.').length - 1).join(".") + "@2x" + "." + @{path}.split('.')[@{path}.split('.').length - 1]`;