LoginSignup
4
4

More than 5 years have passed since last update.

Pugの記述サンプル

Last updated at Posted at 2017-12-19

はじめに

pugでの「ちょっとだけ」便利な記述などを書いているだけなので、
基本的な部分については触れていません。

今回作ったデモ

each

index.pug
    -
     const test = [
      {
        "url": 'https://sample01',
        "text": 'いっこめ',
        "class":'class01'
      },
      {
        "url": 'https://sample02',
        "text": 'にこめ',
        "class":'class02'
      },
      {
        "url": 'https://sample03',
        "text": 'さんこめ',
        "class":'class03'
      },
    ];

    ul
      each item in test
        li
          a(href=`${item.url}`)
            span
              | !{item.text}
            span(class=`${item.class}`)
              | pug

each結果

index.html
    <ul>
      <li>
         <a href="https://sample01">
          <span>いっこめ</span>
          <span class="class01">pug</span>
         </a>
      </li>
      <li>
         <a href="https://sample02">
          <span>にこめ</span>
          <span class="class02">pug</span>
        </a>
      </li>
      <li>
        <a href="https://sample03">
         <span>さんこめ</span>
         <span class="class03">pug</span>
        </a>
      </li>
    </ul>

ul liなどでリストや同じ要素を連続して使うときなどに。
クラス名やurlを変えたりする際は、上記の様に呼び出します。(他にも方法はあると思いますが。)

for

index.pug
   ul
     - for (let i = 0; i < 3; i++)
       li
         h2(class="class" + `${i}`)
           | たいとる
         a(href="#") ぼたん

for結果

index.html
    <ul>
      <li>
        <h2 class="class0">たいとる</h2>
        <a href="#">ぼたん</a>
      </li>
      <li>
        <h2 class="class1">たいとる</h2>
        <a href="#">ぼたん</a>
      </li>
      <li>
        <h2 class="class2">たいとる</h2>
        <a href="#">ぼたん</a>
      </li>
    </ul>

こちらもリストなどを作る時に便利かも。
画像を連続して出す時(picture1.pngとかで管理していたら)

img(src="picture" + `${i}` + ".png")

とかでも使えそう。

変数

index.pug
   - const title = "たいとるだよ";

   h1
     | !{title}   

変数結果

index.html
<h1>たいとるだよ</h1>

まとめ

ベストプラクティスではないとは思いますが、今後も改良して使い勉強していこうと思います。
今度はpug(テンプレートエンジン)の醍醐味でもあるテンプレート作成をしよーかなと。

ソースコード

参考

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