user5770200
user5770200

Reputation:

Thymeleaf: Use a link with 'th:href' in Javascript

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.

Upvotes: 3

Views: 8058

Answers (1)

Stefano Curcio
Stefano Curcio

Reputation: 385

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>

Upvotes: 9

Related Questions