1

I'm trying to hook up a Handlebars.java as a simple view engine for Spring MVC. I've added a Bean for the HandlebarsViewResolver and can get a view to render.

What I'm trying to do now is resolve virtual paths in my views into absolute ones. For example, I have a link to a stylesheet:

<link type="stylesheet" src="/style/theme.css" />

I need the URL to resolve to an absolute path which takes into account the virtual host path the application may be running under. If the application is requested via http://test.site.com/dev/ the URL would resolve to /dev/style/theme.css. For a given request, I can obtain the base path information easily, but the only thing I can think of doing is adding a basePath property to the Handlebars context for every context, and resolve the virtual path by prefix.

<link type="stylesheet" src="{{baseUrl}}/style/theme.css" />

This would mean either having all my models inherit from a base set of properties, or use a HandlerInterceptor to process every model to add in the property.

I've also looked at creating a helper function, but I run into the same problem of having to add to the context for every request, as Spring doesn't seem able to create a ViewResolver for each request, with a dependency on the HttpServletRequest that I could use in the helper function definition.

I can't help but feel this is a really common scenario, one that's catered for in most view engines. Am I missing something really obvious?

Paul Turner
  • 38,949
  • 15
  • 102
  • 166

1 Answers1

0

The HandlerInterceptor is definitely a good option.

Another option can be a ControllerAdvice like:

// Target all Controllers annotated with @HandlebarsController
@ControllerAdvice(annotations = HandlebarsController.class)
public class AnnotationAdvice {

    @Autowired
    ConfigServiceImpl configService;

    @ModelAttribute("baseUrl")
    public String getBaseUrl() {
       return configService.findBaseUrl();
    }
}

Spring MVC Controller Advice

Tasos Zervos
  • 526
  • 1
  • 6
  • 8