Skip to content

Instantly share code, notes, and snippets.

@MartinKnopf
Last active December 19, 2015 06:49
Show Gist options
  • Save MartinKnopf/5913954 to your computer and use it in GitHub Desktop.
Save MartinKnopf/5913954 to your computer and use it in GitHub Desktop.
Wicket: Merging multiple CSS files into one
package org.horsed.wicket.cssmerger;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.wicket.markup.head.CssContentHeaderItem;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.request.resource.CssResourceReference;
public class CssMerger {
private final String id;
private final List<CssResourceReference> refs = new ArrayList<CssResourceReference>();
public CssMerger(String id) {
this.id = id;
}
public CssMerger addCss(Class<?> scope, String name) {
refs.add(new CssResourceReference(scope, name));
return this;
}
public CssContentHeaderItem build() {
StringBuilder sb = new StringBuilder();
for (CssResourceReference ref : refs) {
try {
String filename = ref.getResource().getResourceStream().toString().replace("file:/", "")
.replace("target/classes", "src/main/java");
String style = FileUtils.readFileToString(new File(filename));
sb.append(style);
} catch (IOException e) {
e.printStackTrace();
}
}
return CssHeaderItem.forCSS(sb.toString(), id);
}
public void install(IHeaderResponse response, boolean merge) {
if (merge) {
response.render(this.build());
} else {
for (CssResourceReference ref : refs) {
response.render(CssHeaderItem.forReference(ref));
}
}
}
}
package org.horsed.wicket.cssmerger;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.request.mapper.parameter.PageParameters;
public class HomePage extends WebPage {
public HomePage(final PageParameters parameters) {
super(parameters);
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
new CssMerger("merged.css") //
.addCss(HomePage.class, "styles/style.css") //
.addCss(HomePage.class, "styles/comp.css") //
.install(response, false);
}
}
@moadqassem
Copy link

Hello Horsed,

What about the children of the component ?

imagine you have HomePage.class that inherits another classes and those classes basically are components, so how you can merge the css files of the sub classes into one css file ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment