LoginSignup
0
0

More than 3 years have passed since last update.

VSCodeにThymeleaf用のスニペットを作ろう

Posted at

はじめに

VSCodeでのユーザースニペットの記事は調べればあるが、Thymeleaf用のものがなく、VSCodeのプラグインでもいい感じのものがなかったため備忘録的に書いておこうと思う。
※検証環境はmacOS Mojave 10.14.16

スニペットとは

直訳すると「切れ端」や「断片」となるが、要は呼び出したいものに名前を付けて簡単に呼び出せるようにしたものということ。

早速試してみる

「Shift+Command+p」を押すと、画面上部に検索画面が出てくるのでuserなどと打つと「Preferences: Configure User Snippets」が出てくるからこれを選択。
スクリーンショット 2020-01-17 6.17.10.png
次に、言語選択画面が出てくるので今回はhtmlを入力し、html.jsonを選択し開く
スクリーンショット 2020-01-17 6.21.32.png
この中にスニペットを書いていけばhtmlの中で呼び出すことができます。

"Thymeleaf value": {
    "prefix": "tval",
    "body": "th:value=\"\\${$1.$2}\"",
},

解説

"Thymeleaf value"
スニペット名…スニペットの名前を決めます。(このファイルの中で区別するためのもの)
"prefix": "tval",
実際に入力する単語…この文字をhtmlファイルで入力することで呼び出せます。
"body": "th:value=\"\\${$1.$2}\"",
呼び出されるもの…prefixを入力するとこちらが呼び出されます。
1行の場合は、""の中、2行以上の場合は[]で入れてください。
\$1…呼び出された後の入力位置tabキーを押すと\$2、\$3と移動することができます。
\…"は\、\$は\\など、特殊文字を単なる文字列として使いたい場合は、エスケープしてください。

実演

qiita_thymeleaf.gif
こんな感じで動きます。

Thymeleaf用に作成

では、これをThymeleaf用に作成していきたいと思います。

"Thymeleaf comment": {
    "prefix": "tcom",
    "body": "<!--/* $1 */-->",
},
"Thymeleaf value": {
    "prefix": "tval",
    "body": "th:value=\"\\${$1.$2}\"",
},
"Thymeleaf text": {
    "prefix": "ttex",
    "body": "th:text=\"\\${$1.$2}\"",
},
"Thymeleaf local": {
    "prefix": "twit",
    "body": "th:with=\"x=$1,y=$2\"",
},
"Thymeleaf link": {
    "prefix": "tlink",
    "body": "th:href=\"\\@{'/' + \\${$1.$2}}\"" ,
},
"Thymeleaf if": {
    "prefix": "tif",
    "body": "th:if=\"\\${$1}\"" ,
},
"Thymeleaf unless": {
    "prefix": "tif",
    "body": "th:unless=\"\\${$1}\"" ,
},
"Thymeleaf switch": {
    "prefix": "tswit",
    "body": [
        "<div th:switch=\"\\${$1}\">",
        "\t<p th:case=\"$2\" th:text=\"\\${$3}\"></p>",
        "\t<p th:case=\"$4\" th:text=\"\\${$5}\"></p>",
        "\t<p th:case=\"*\">対象なし</p>",
        "</div>"
    ] ,
},
"Thymeleaf for": {
    "prefix": "tfor",
    "body": [
        "<tr th:each=\"$2 : \\${$1}\">",
        "\t<td th:text=\"\\${$3.$4}\"></td>",
        "\t<td th:text=\"\\${$5.$6}\"></td>",
        "\t<td th:text=\"\\${$7.$8}\"></td>",
        "</tr>",
    ] ,
},

あとがき

とりあえず最近使っているものだけまとめましたが、他にもThymeleafの記法はあるので随時追加して使っていきたいと思います。また、これを改変すれば他の言語にも応用できるので積極的に使用していこうと思いました。

参考にした記事

0
0
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
0
0