Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom function in thymeleaf

Tags:

java

thymeleaf

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.

like image 327
OMGKurtNilsen Avatar asked Jul 24 '26 02:07

OMGKurtNilsen


1 Answers

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;
}
like image 161
cdalxndr Avatar answered Jul 25 '26 14:07

cdalxndr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!