Tapestry 5 - Dynamically generate URL of file in w

2019-04-10 17:33发布

问题:

I am displaying a static image asset inside a component, and I don't know until runtime what that image should be, so I need to dynamically generate the URL. These images all live in webapp/images/

The documentation I found is not very clear on how to handle this usecase, but after playing around I figured out I can construct the URL dynamically in the component template like so:

<img src="${context:img/score/overall}/${imageFilename}" />

Then put the logic for which image to display in the component class file:

public String getImageFilename() {
    // decide which image to display and return the filename
}

So this works, but it's not the cleanest solution. I don't really want to concatenate the URL base to the filename inside the template - I'd much rather construct the entire URL in the component class, like so:

<img src="${imageUrl}" />

and

public String getImageURL() {
    // build URL somehow like "context:" + "filePath" in template
}

So my question is: Is there a Java code equivalent of context: ... in the template that simply produces a String base URL for the web appl context folder that I can append my file path to?

I can see some obvious hacky ways of doing it from reading the docs, like manually constructing the base URL using the scheme described, or injecting a known static image as an Asset from the web app context folder and calling toClientURL() to extract the base URL. But it seems like there must be a nice built-in way to do this in Java, especially since it's freely available to use in a template expansion.

But google as I might, I can't seem to find how to do this anywhere!

回答1:

I think this should do the trick for you. (disclaimer: I have not tested it)

@Inject
private AssetSource assetSource;

@Inject
private Locale locale;

public String getImageURL() {
    URL assetUrl = assetSource.getContextAsset("img/score/overall/" + getImageFilename(), locale).toURL();
    return assetUrl.toString();
}

Edit: Updated to reflect Howards comment



标签: java tapestry