LoginSignup
3
4

More than 3 years have passed since last update.

【Thymeleaf】th:hrefをJavaScriptで使う

Last updated at Posted at 2020-05-26

詰まったこと

th:hrefをJavaScriptで生成すると、機能しない。

Thymeleafでは、hrefを使うとき、次のような書き方をすると思います。

<a th:href="@{/hello}">サンプル</a>

html上では上手くいきますが、
これを次のようにJavaScriptで生成すると、機能しません。

<script type="text/javascript">
    target.html('<a th:href="@{/hello}">サンプル</a>');
</script>

困った。。。

解決法

①まず、scriptタグを書き換えます。

<script type="text/javascript" th:inline="javascript">

②リンクを定義します。

const link = /*[[@{/hello}]]*/'';

/helloを飛ばしたいリンクにしてください。

③ ②で定義したリンクに書き換える。

target.html('<a href="' + link + '">サンプル</a>');

ここでのポイントは、

<a th:href...

とせずに、

<a href...

とすることです。

まとめると、

<script type="text/javascript" th:inline="javascript">
    const link = /*[[@{/hello}]]*/'';
    target.html('<a href="' + link + '">サンプル</a>');
</script>

パラメーターを付与したい時は?

パラメータを付与したい時、あると思います。
そんな時は、、、

const baselink = /*[[@{/samplek}]]*/'';
const link = baselink + "?id=" + id;
target.html('<a href="' + link + '">サンプル</a>');

上手くできました。

以上です。最後まで読んでくださり、ありがとうございました。

参考

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

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4