admin管理员组

文章数量:1294643

I have the following link:

<a th:href="@{/linkToPage}">...</a>

which works. But now I have a workaround where I have to "create" this link in Javascript:

$('#div').html(
    '<a th:href="@{/linkToPage}">...</a>'
);

but now the link does not work anymore. Is there a way to get link work and call the corresponding 'get' method in the controller? Thank you very much.

I have the following link:

<a th:href="@{/linkToPage}">...</a>

which works. But now I have a workaround where I have to "create" this link in Javascript:

$('#div').html(
    '<a th:href="@{/linkToPage}">...</a>'
);

but now the link does not work anymore. Is there a way to get link work and call the corresponding 'get' method in the controller? Thank you very much.

Share Improve this question edited Aug 13, 2018 at 8:35 asked Aug 10, 2018 at 12:11 user5770200user5770200 3
  • Thymeleaf templates are usually executed on server-side while, javascript is usually executed on clients browser. So the browser rendering engine does not know th:ref attributes. Using plain javascript, i guess you can only set the link target without th: prefix – Andre Albert Commented Aug 10, 2018 at 12:16
  • That works! But generally: is it a good idea to do it that way (btw: I am using Spring MVC and calling a get-method in the controller) – user5770200 Commented Aug 10, 2018 at 12:18
  • i am not familiar with Spring MVC but using the thymeleaf engine in different context. If it is related with Spring MVC you might want to add a Spring MVC related Tag to notify a different audience of experts here too – Andre Albert Commented Aug 10, 2018 at 12:20
Add a ment  | 

1 Answer 1

Reset to default 9

You can achieve it using Thymeleaf script inlining. Try to add th:inline="javascript" to the script tag and initizialize a link variable to use it in your script as follows. You can find out more about Thymeleaf script inlining here.

<script type="text/javascript" th:inline="javascript">
/*<![CDATA[*/

    var link = /*[[@{/linkToPage}]]*/'';

    $('#div').html(
        '<a href="' + link + '">...</a>'
    );

 /*]]>*/
 <script>

本文标签: Thymeleaf Use a link with 39thhref39 in JavascriptStack Overflow