Help us understand the problem. What is going on with this article?

【備忘録】pug の変数の書き方いろいろ

More than 1 year has passed since last update.

変数定義の時の行頭の「-(ハイフン)」は最初だけでよい

最初に「-(ハイフン)」入れて、改行&インデントでその後は不要

pug
//-  最初知らなくてやってた面倒な書き方
- var aaa = "hoge";
- var bbb = "fuga";

//-  改行&インデントすれば1個で済む
-
    var aaa = "hoge";
    var bbb = "fuga";

連想配列も使える

連想配列を定義したら each ... in で取り出す

pug
//-  連想配列例
-
    var obj = {
        title : 'hoge',
        description : 'fugafuga.',
        img : './hoge.jpg',
        date : '2017/12/8'
    }

//-  取り出し
//-  配列のキーと値の取り出し順が逆なのがちょっと気持ち悪い。。。
ul
    each val, key in obj
        li(class=key) !{val}

配列に入れた連想配列も使える

同じく each ... in で取り出す

pug
//-  配列に入れた連想配列
-
    var arr = [
        {
            title : 'hoge1',
            description : 'fugafuga1.',
            img : './hoge1.jpg',
            date : '2017/12/8'
        },
        {
            title : 'hoge2',
            description : 'fugafuga2.',
            img : './hoge2.jpg',
            date : '2017/12/9'
        },
        {
            title : 'hoge3',
            description : 'fugafuga3.',
            img : './hoge3.jpg',
            date : '2017/12/10'
        }
    ];
//-  取り出し
ul
    each val in arr
        li
            h2 #{arr.title}
            p #{arr.description}
            img(src=arr.img)
            p #{arr.date}

mixinへの代入もできる

pug
//-  変数は上記と同じものとする

//-  mixin定義
mixin set_list(_title, _desc, _img, _date)
    li
        h2 #{_title}
        p #{_desc}
        img(src=_img)
        p #{_date}

//-  取り出し
ul
    each val in arr
        set_list(arr.title, arr.description, arr.img, arr.date)

単体で文字列として出力したい時や属性値として使う時、引数として使う時などで微妙に書き方が変わるのでよく間違える。。

yuusuke510
色々勉強中です。
d2cdot
テクノロジーの力で『伝えたいコトを伝わるカタチに』
https://www.d2cdot.co.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした