John Ehrmantraut John Ehrmantraut - 3 years ago 16859
Twig Question

Vue.js can't set background-image in :style (twig template)

I'm using Vue.js at my Symfony 3.4 project.

I have a problem with seting my background-image from object via Vue.js

I'm looping through my elements via Vue and just inserting some data from object.
Everything is fine instead of the image.

<tr v-for="user in userObj">
<div class='table-image'
:style="{ 'background-image' : 'url(' + user.image + ')' }">

I was trying
:style="{ 'background-image' : 'url(' + user.image + ')' }">

:style="{ 'backgroundImage' : 'url(' + user.image + ')' }">

:style="{ backgroundImage : 'url(' + user.image + ')' }">

NOTHING is working :(

Can someone help me with that?

I'm using it in TWIG template.

Vue.js v2.5.11

EDIT! just in case.

Vue is removing
attribute and not inserting anything, I mean: at the source code I just can see
<div class='table-image'></div>
without style.

Answer Source

When making a css style selector, it is important to quote any part containing special characters.

At the moment, when you output a url, it is outputted as backgroundImage: url(/im/test.png). As you probably notice, there is no quoting of the value.

While your method works when the input has no special characters, when any special character is included, undefined behaviour will be emitted.

You should add quotes to the style declaration:

:style="{ 'background-image' : 'url(\'' + user.image + '\')' }"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download