Skip to content
Advertisement

Display images dynamically using jquery and thymeleaf

I am trying to display image dynamically by using jquery append function with thymeleaf as view engine in spring boot

Here is the way that I tried to append the image to div (‘.show-image’):

success: function (data) {
    var image_url = "images.png";
    var images_div = "<img th:src="@{/image/"+image_url+"}" height="360px" width="400px">";
    $('.show-image').append(images_div);
}

However, it only shows the empty images (no 404 error)

I tried with other random online image and works:

success: function (data) {
    var images_div = "<img src="https://onlinejpgtools.com/someimage/random-grid.jpg" height="360px" width="400px">";
    $('.show-image').append(images_div);
}

When I statically display the image also works (I think no path issue):

<div class="show-image">
    <img th:src="@{/image/images.png}"  height="360px" width="400px">
</div>

Any suggestions?

Advertisement

Answer

Turns out thymeleaf is a server side technology, which it won’t render any new images.

I think my design was wrong, and I just need to render the image without using thymeleaf like this:

success: function (data) {
    var image_url = "images.png";
    var images_div = "<img src=""+image_url+ "" height="360px" width="400px">";
    $('.show-image').append(images_div);
}

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement