【问题标题】:Thymeleaf custom dialect with fragmentsThymeleaf 带有片段的自定义方言
【发布时间】:2018-11-22 14:05:39
【问题描述】:

在我的 Spring Boot 2 项目中,我有 Thymeleaf 片段来生成表单元素。例如:

<input th:replace="component/admin_form :: text (formElement = ${vm.getElementStatus()}, class='css-class-a'))" />

上面的代码生成了一个复杂的 div 块,带有标签、输入字段和错误块。

我想简化这个语法。我的想法是创建一个带有自定义标签的自定义方言并写下这个:

<admin-form:text value="${vm.getElementLastName()}" class="css-class-a"/>

第二个更容易阅读,它清楚地向设计师表明这是一个特殊的元素。除此之外,更改主题会更容易,因为我只需要更改标签处理器中的具体片段位置,而不是数百个 th:replace 值。

同样重要的是,我不想在标签处理器中构建复杂的 html 布局,只想以某种方式导入片段。所以设计者可以在不修改java代码的情况下修改html片段。

我能够创建自定义方言并创建生成 html 块的自定义标记:

@Override
protected void doProcess(ITemplateContext context, IProcessableElementTag tag, IElementTagStructureHandler structureHandler) {
    final IModelFactory modelFactory = context.getModelFactory();
    final IModel model = modelFactory.createModel();

    model.add(modelFactory.createOpenElementTag("div", "class", "test"));
    model.add(modelFactory.createText("This is my custom element"));
    model.add(modelFactory.createCloseElementTag("div"));

    structureHandler.replaceWith(model, false);
} 

但我不知道如何在我的自定义标签中导入片段。

有可能吗?

【问题讨论】:

    标签: spring-mvc thymeleaf


    【解决方案1】:

    &lt;admin-form:text&gt; 标记的doProcess 可以创建一个具有包含“复杂输入”片段的th:replace 属性的虚拟标记:

    Map<String, String> attributes = new HashMap<>();
    attributes.put("th:replace", "/pathToMyFragment/complexInput::myfragname");
    IOpenElementTag newTag = modelFactory.createOpenElementTag("div", attributes, AttributeValueQuotes.DOUBLE, false);
    model.replace(0, newTag);
    

    或类似的东西(注意关闭标签等)。

    结果是替换

    <admin-form:text/>
    

    <div th:replace="/pathToMyFragment/complexInput::myfragname"></div>
    

    依次被处理成最终的 HTML。 如果您需要保留原始标签属性(如class="css-class-a"),您可以使用model.get(0).getAttributeMap() 从原始标签中获取它们,并将它们添加为带有structureHandler.setLocalVariable("originalAttributes", theAttributeMap); 的局部变量,以在最终片段中使用,例如。

    【讨论】:

      猜你喜欢
      • 2021-10-21
      • 2015-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      • 1970-01-01
      • 2014-04-28
      相关资源
      最近更新 更多