Displaying image in GSP (Grails), get link from database

11,322

The proper syntax to avoid a syntax errors would be:

<img src="${resource(dir:'images', file:fieldValue(bean:productInstance, field:'image'))}" />

But I recommend you write your own tagLib, because it is really very simple to write one and your GSPs will look much nicer if you are going to use this code a lot. You could easily write a tag that would be called something like: <product:image product='productInstance' /> and for extra usability you could make the tagLib output the link as well.

The simplicity of writing tagLibs is really one of the best grails features in my opinion.

Share:
11,322
Hoàng Long
Author by

Hoàng Long

I'd like to describe myself as an adventurer who seeks to explore new knowledge. But actually, I'm just an ordinary people, struggling hard to make the life a little better.

Updated on June 07, 2022

Comments

  • Hoàng Long
    Hoàng Long almost 2 years

    I'm a Grails newbie. I'm trying to show an images thumbnail for every product in a site, like this:

    <a href="#"><img src="${resource(dir:"images", file: "Nikon.jpg") }"/></a>/* 1 */
    

    The problem here is that I want to save the image link in the database, and get the link by:

    ${fieldValue(bean: productInstance, field: "image")}  /* 2 */
    

    But I can't replace the /* 2 / code into the places of "Nikon.jpg" in / 1 */, it causes syntax error!

    After doing some research, I see that most tutorials show how to display image that stores directly in database (for example, How to display image in grails GSP?). I'm not sure if that approach is better, but I still want to take image link from database.

    I also tried to search grails tag library to find any support tag, but with no success. Can anyone give me a hint?

  • Hoàng Long
    Hoàng Long over 13 years
    Thanks Michael for your reply. It works, but I want to start my path at the web-app folder. The resource keyword helps me to do that automatically. With your way, I must use the link: <myproject>/images/Nikon.jpg . Can I just save "Nikon.jpg" or "/images/Nikon.jpg" ?
  • Hoàng Long
    Hoàng Long over 13 years
    Thanks for your answer, it's finished now. I'm going to spend more time studying tagLib next!