Skip to content

Instantly share code, notes, and snippets.

@subchen
Created November 15, 2013 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save subchen/7481744 to your computer and use it in GitHub Desktop.
Save subchen/7481744 to your computer and use it in GitHub Desktop.
function assetsUrl(path) for jetbrick-template
import java.io.File;
import java.io.FilenameFilter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import jetbrick.template.runtime.JetPageContext;
import jetbrick.template.web.JetWebContext;
public class AssetsUrlFunctions {
private static Map<String, String> mapping = new HashMap<String, String>(128);
public static String assetsUrl(JetPageContext ctx, String path) {
String url = mapping.get(path);
if (url != null) {
return url;
}
ServletContext sc = (ServletContext) ctx.getContext().get(JetWebContext.SERVLET_CONTEXT);
url = "/assets/" + path;
File file = new File(sc.getRealPath(url));
if (!file.exists()) {
int pos = file.getName().lastIndexOf(".");
if (pos > 0) {
final String nameWithoutExt = file.getName().substring(0, pos);
final String ext = file.getName().substring(pos);
File[] files = file.getParentFile().listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith(nameWithoutExt + "-") && name.endsWith(ext);
}
});
if (files != null && files.length > 0) {
url = url.replaceFirst("([^/\\\\]+)$", files[0].getName());
}
}
}
url = sc.getContextPath() + url;
mapping.put(path, url);
return url;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment