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

grailsgsp

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?

Best Answer

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.

Related Topic