Solon

solon.view.thymeleaf

v2.7.5 </> markdown
<dependency>
    <groupId>org.noear</groupId>
    <artifactId>solon.view.thymeleaf</artifactId>
</dependency>

1、描述

视图扩展插件,为 Solon View 提供基于 thymeleaf 的框架适配。

2、应用示例

DemoController.java

//顺便,加个国际化在模板里的演法
@I18n
@Controller
public class DemoController{
    @Mapping("/test")
    public ModelAndView test() {
        ModelAndView model = new ModelAndView("thymeleaf.html");
        model.put("title", "dock");
        model.put("msg", "你好 world!");

        return model;
    }
}

resources/WEB-INF/templates/thymeleaf.html(使用th:replace属性需要带上完整文件名)

<!DOCTYPE html>
<html>
<head>
    <title th:text="${title}"></title>
    <script th:src="@{/js/common.js}" charset="utf-8"></script>
</head>
<body>
<head th:replace="headPart.html::head('主页')"></head>
<main>
thymeleaf::<span th:text="${msg}"></span>;i18n::<span th:text='${i18n.get("login.title")}'></span>
</main>
</body>
</html>

3、支持事件扩展定制示例

public class App {
    public static void main(String[] args) {
        Solon.start(App.class, args, app->{
            app.onEvent(TemplateEngine.class, e -> {
                //可能会获取两次事件(一个是 debug 模式下才有的)
            });
        });
    }
}

4、自定义标签示例

以插件自带的权限验证标签为例:

<auth:permissions name="user:del">
    我有user:del权限
</auth:permissions>

自定义标签和共享变量代码实现:

@Component("view:authPermissions")
public class AuthPermissionsTag extends AbstractElementTagProcessor {

    public AuthPermissionsTag(String dialectPrefix) {
        super(TemplateMode.HTML, dialectPrefix, AuthConstants.TAG_permissions, true, null, false, 100);
    }

    @Override
    protected void doProcess(ITemplateContext context, IProcessableElementTag tag, IElementTagStructureHandler structureHandler) {
        String nameStr = tag.getAttributeValue(AuthConstants.ATTR_name);
        String logicalStr = tag.getAttributeValue(AuthConstants.ATTR_logical);

        if (Utils.isEmpty(nameStr)) {
            return;
        }

        String[] names = nameStr.split(",");

        if (names.length == 0) {
            return;
        }

        if (AuthUtil.verifyPermissions(names, Logical.of(logicalStr)) == false) {
            structureHandler.setBody("", false);
        }
    }
}

@Component("share:demo1")
public class Demo {
    public String hello(){
        return "hello";
    }
}