thymeleaf利用fragment解决html页面间获取context-path问题
问题说明 我使用spring boot+thymeleaf做了个项目,那前台页面都是html,里面有各种api调用和路径跳转。 大家都知道这些路径不能写死,为保证任何情况下路径的正确性,一般都是这种格式: 项目路径 +接口路径,例如:localhost:8080/system/api/user/1 现在已知thymeleaf页面中js要获取项目路径时这样的: <script type="text/javascript" th:inline="javascript"> /*<![CDATA[*/ var ctx = /*[[@{/}]]*/ ''; /*]]>*/ </script> ctx=/system/ 那我又不想每个页面都写这么一段,所以利用thymeleaf的片段引用特性可以把它抽成公共脚本供各html页面用。 解决方法 1.创建fragment.html <script type="text/javascript" th:inline="javascript" th:fragment="ctx"> /*<![CDATA[*/ var ctx = /*[[@{/}]]*/ ''; /*]]>*/ </script> 2.页面引用 <!--ctx--> <script th:replace="~{fragment::ctx}"/> 3.调整接口和路径格式 $.get(ctx+