我使用 thymeleaf 模板设置了 servlet,但我不知道如何在 thymeleaf 中创建自定义函数或类似的功能。
我基本上想要这样的东西:
<img th:src="${createJpegUrl(640,1,0.7,'some-key')}" />
Run Code Online (Sandbox Code Playgroud)
这呈现为:
<img src="/640/1/0.7/some-key.jpg"/>
Run Code Online (Sandbox Code Playgroud)
我一直在谷歌上搜索并查看文档,但没有进一步了解。
您可以创建一个辅助类:
public class JpegHelper {
public static JpegHelper getInstance() {...}
public String createJpegUrl( int w, int h, double d, String key {
...
}
}
Run Code Online (Sandbox Code Playgroud)
然后将其添加到控制器中的模型中:
modelAndView.getModelMap().addAttribute( "jpegHelper", JpegHelper.getInstance() );
Run Code Online (Sandbox Code Playgroud)
并在你的 thymeleaf 模板中使用它:
<img th:src="${jpegHelper.createJpegUrl(640,1,0.7,'some-key')}" />
Run Code Online (Sandbox Code Playgroud)
如果您希望该助手可用于所有模板而不将其添加到模型中,请在 spring 配置中注册它:
@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;
}
Run Code Online (Sandbox Code Playgroud)
扩展 AbstractAttrProcessor 将使您可以匹配特定的属性。
我最终扩展了 AbstractElementProcessor 并将其添加到 StandardDialect 中。这是因为我需要做一些额外的事情。
| 归档时间: |
|
| 查看次数: |
5833 次 |
| 最近记录: |