Wednesday, August 20, 2014

omg wicket finally added the best feature ever!

well it was finally added a long time ago, i just never bothered to check. but its now possible and extremely simple to use wicket for email templates. no more ant-style variables with archaic templating engines like velocity and freemarker. here's a quick example:

in some arbitrary class i have...

public class EmailSendingClass {
public void sendWelcomeEmail(User user) {
log.warn("send welcome message for user: {}", user.getId());

Component component = new WelcomeEmail("email", new UserModel(user));
CharSequence body = ComponentRenderer.renderComponent(component);

then i have a WelcomeEmail class...

public class WelcomeEmail extends Panel {
private static final long serialVersionUID = 1L;

public WelcomeEmail(String id, IModel<User> user) {
super(id, new CompoundPropertyModel<User>(user));

add(new Label("email"));

and finally the corresponding markup...


<p>You have successfully created an account.</p>
<p>Use your email address <span wicket:id="email"></span> to login.</p>


the magic part here is of course the org.apache.wicket.core.util.string.ComponentRenderer class that renders a wicket component as a string. you can now take that text and print it to a log file or perhaps something more interesting like sending an email. for the plain text version, don't forget to add .setRenderBodyOnly(true) to each Label, etc.

No comments: