简体   繁体   中英

grails asset pipeline: how to find image url dynamically in javascript (with knockout)

What's the best practice when you have a number of image assets that might change on a page (because you're creating part of the DOM on the fly with Knockout, Angular, whatever) and you need to put together the URL?

For simplicity sake, suppose I have a set of images that represent progress from 0 to 100 percent, and I want to insert a chunk of code that effectively does something like this:

var oImg=document.createElement("img");
var percent = calculateSomeOtherThingHere();
oImg.setAttribute('src', 'SOME URL GOES HERE%/pctImage' + percent);
document.body.appendChild(oImg);

Additionally, how do I ensure that the asset pipeline understands that I might need any of those images (from pctImage0 to pctImage100) when rendering the page?

Any clues anyone? Thanks.

If you are using grails 3.x with the assets plugin, you could insert this code in the view (or in the layout) gsp file:

<g:javascript>
    var grailsRes = {
        pctImage1 : '${assetPath(src: '1.jpg')}',
        pctImage2 : '${assetPath(src: '2.jpg')}',
        pctImage3 : '${assetPath(src: '3.jpg')}',
        //...
        pctImage98 : '${assetPath(src: '98.jpg')}',
        pctImage99 : '${assetPath(src: '99.jpg')}',
        pctImage100 : '${assetPath(src: '100.jpg')}'
    };
</g:javascript> 

Then, change your javascript code to something like this:

var oImg=document.createElement("img");
var percent = calculateSomeOtherThingHere();
oImg.setAttribute('src', grailsRes['pctImage' + percent]);
document.body.appendChild(oImg);

For a simpler code you could use an array with index access.

Check the grails assets plugin documentation here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM