如何使用 ThymeLeaf 生成包含“#”的 href 链接?

问题描述 投票:0回答:1

在我的模板中,我必须生成一个类型的链接

<a href="http://myhost/myapp/#/products/12345/details">. . .</a>

'12345'是可变部分。

该链接是 ID=12345 的产品详细信息的“深层链接”。 URL 中的“#”必须存在,因为显示详细信息的 Web 框架需要它(我认为它是单页 Web 应用程序)。

如果我的模板中有这个:

<a th:href="@{http://myhost/myapp/#/products/{productId}/details(productId=${product.id})}">. . .</a>

然后生成的链接看起来像

.../myapp?productId=12345#/products/{productId}/details

即以“#”开头的部分先被截掉,然后逐字附加;该参数作为查询字符串附加到 URL(带有“?”)。

如果我在模板中有这个(即我将哈希符号作为变量的一部分,这样 URL 的这一部分就不会被切断):

<a th:with="productLink=${'#/products/' + product.id + '/details'}"
   th:href="@{http://myhost/myapp/{productLink}(productLink=${productLink})}">. . .</a>

然后我几乎得到了我想要的,但是 URL 中的“#”被编码为“%23”:

<a href="http://myhost/myapp/%23/products/12345/details">. . .</a>

如何生成应有的 URL,即在正确的位置使用井号和产品 id - 请参阅问题的开头。

如果重要的话,该应用程序是基于 SpringBoot 的应用程序。

thymeleaf spring-thymeleaf
1个回答
0
投票

你可以使用javascript来解决这个问题,我不认为ThymeLeaf会允许在href中使用@signe: 给它一个类来访问它:

<a 
class=" link-requires-fixing " // add your class here
th:href="@{http://myhost/myapp/#/products/{productId}/details(productId=${product.id})}">. . .</a>

然后更改 href 属性

document.addEventListener("DOMContentLoaded", () => {

   const linksToFix = document.querySelectorAll(".link-requires-fixing");

    linksToFix.forEach(link => {
      const originalHref = link.getAttribute("href");
      const updatedHref = originalHref ? originalHref.replace("%23", "#") : "";
      link.setAttribute("href", updatedHref);
    });

  
});
© www.soinside.com 2019 - 2024. All rights reserved.