Thymeleaf 3.1中替换片段时如何为传入的SVG元素添加类名?
解决Thymeleaf 3.1中SVG片段替换丢失class的问题
针对你遇到的th:replace替换SVG时丢失宿主标签class、th:include导致嵌套SVG缩放异常,且不想给大量SVG加参数的问题,提供以下两个实用方案:
方案1:拆分SVG片段为内容部分,保留tile中的SVG根标签
将SVG片段定义为不含根<svg>标签的纯图形内容(如path、g等),在tile片段中维护带class的SVG根标签,直接插入图形内容:
步骤1:定义SVG内容片段
<!-- svg/notification-icon.html --> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z"/>
步骤2:编写tile片段
在tile中保留带Tailwind类的SVG根标签,用th:replace插入SVG内容:
<!-- fragments/tile.html --> <div class="tile"> <svg th:class="${svgClass ?: 'w-16 h-16 p-6'}" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" > <th:block th:replace="${svgContent}" /> </svg> <!-- 其他tile元素,比如标题、描述 --> <h3 th:text="${title}"></h3> </div>
调用tile片段
默认使用tile中定义的class,需要自定义时传入svgClass参数:
<!-- 页面中调用tile --> <div th:replace="fragments/tile :: tile(svgContent='svg/notification-icon.html')"></div> <!-- 自定义尺寸 --> <div th:replace="fragments/tile :: tile(svgContent='svg/user-icon.html', svgClass='w-20 h-20 p-3')"></div>
优点:完全保留Tailwind内联样式的写法,无嵌套SVG缩放问题,无需修改现有大量SVG片段(只需移除根<svg>标签)。
方案2:给SVG片段添加可选class参数,通过th:replace传递
如果不想修改现有SVG片段的结构(保留根<svg>标签),可以给SVG片段添加可选的class参数,在调用tile时传递样式:
步骤1:修改SVG片段,添加class参数
给SVG的根标签添加th:class,设置默认空值:
<!-- svg/settings-icon.html --> <svg th:class="${svgClass ?: ''}" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" > <path d="M19.43 12.98c.04-.32.07-.64.07-.98s-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.12-.22-.39-.3-.61-.22l-2.49 1c-.52-.39-1.08-.7-1.66-.94l-.38-2.65c-.03-.24-.24-.42-.48-.42h-4c-.24 0-.45.18-.48.42l-.38 2.65c-.58.24-1.14.55-1.66.94l-2.49-1c-.22-.08-.49 0-.61.22l-2 3.46c-.12.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98s.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.12.22.39.3.61.22l2.49-1c.52.39 1.08.7 1.66.94l.38 2.65c.03.24.24.42.48.42h4c.24 0 .45-.18.48-.42l.38-2.65c.58-.24 1.14-.55 1.66-.94l2.49 1c.22.08.49 0 .61-.22l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zM12 15.5c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5 3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z"/> </svg>
步骤2:编写tile片段
调用SVG片段时传递class参数:
<!-- fragments/tile.html --> <div class="tile"> <svg th:replace="${svgFragment} :: svg(svgClass='w-16 h-16 p-6')" /> <h3 th:text="${title}"></h3> </div>
调用tile片段
<div th:replace="fragments/tile :: tile(svgFragment='svg/settings-icon.html', title='设置')"></div>
优点:无需修改SVG片段的内容结构,仅需添加一行th:class代码,适合已有大量完整SVG片段的场景。
内容的提问来源于stack exchange,提问作者iansedano
相关产品推荐
相关产品推荐

