I have my servlet set up with thymeleaf templates, but I have no idea how to create a custom function or something similar in thymeleaf.
I basically want something like this:
<img th:src="${createJpegUrl(640,1,0.7,'some-key')}" />
That renders to:
<img src="/640/1/0.7/some-key.jpg"/>
I have been googling around and looking at the documentation without getting much closer.
You can create a helper class:
public class JpegHelper {
public static JpegHelper getInstance() {...}
public String createJpegUrl( int w, int h, double d, String key {
...
}
}
then add it to the model in your controller:
modelAndView.getModelMap().addAttribute( "jpegHelper", JpegHelper.getInstance() );
and use it in your thymeleaf template:
<img th:src="${jpegHelper.createJpegUrl(640,1,0.7,'some-key')}" />
If you want the helper to be available to all templates without adding it to the model, then register it in your spring configuration:
@Bean
public ThymeleafViewResolver thymeleafViewResolver( @Autowired SpringTemplateEngine templateEngine ) {
ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver();
thymeleafViewResolver.setTemplateEngine( templateEngine );
thymeleafViewResolver.setCharacterEncoding( "UTF-8" );
thymeleafViewResolver.addStaticVariable( "jpegHelper", JpegHelper.getInstance() );
return thymeleafViewResolver;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With