1

我目前正在学习 Pug/Jade 中的迭代。我想继续使用这个工具。

在下面的代码中,您基本上拥有相当于滑块的内容。

在第一个实例中,#{i}应该为每个列出的类返回值 1-4,但编译时却是一样的。虽然我已经看到这种技术对其他人有用。

其次,关于我的data数组,我已经能够获得title在 each 中显示的值section,但是,让button值出现在同一个容器中似乎是一个挑战。

- var data=[{'title':'Home Run', 'button':'It\'s a win'}, {'title':'Testing', 'button':'Tested'}, {'title':'Foreground', 'button':'Background'}, {'title':'Forest', 'button':'Trees'}]


.slide-container
  - var i=0;
    while (i++ < 4)
      mixin list(title)
        section(class='slide-#{i}')
            h2= title


  each item in data
    +list(item.title)
    a(href='#')= item.button

上面的代码返回以下内容:

<div class="slide-container">
    <section class="slide-#{i}">
      <h2>Home Run</h2>
    </section><a href="#">It's a win</a>
    <section class="slide-#{i}">
      <h2>Testing</h2>
    </section><a href="#">Tested</a>
    <section class="slide-#{i}">
      <h2>Foreground</h2>
    </section><a href="#">Background</a>
    <section class="slide-#{i}">
      <h2>Forest</h2>
    </section><a href="#">Trees</a>
</div>

这很棒,但不是我需要的。我真正希望看到编译的是以下内容:

<div class="slide-container">
    <section class="slide-1">
      <h2>Home Run</h2>
      <a href="#">It's a win</a>
    </section>
    <section class="slide-2">
      <h2>Testing</h2>
      <a href="#">Tested</a>
    </section>
    <section class="slide-3">
      <h2>Foreground</h2>
      <a href="#">Background</a>
    </section>
    <section class="slide-4">
      <h2>Forest</h2>
      <a href="#">Trees</a>
    </section>
</div>

笔可以在这里查看:https ://codepen.io/jobaelish/pen/jYyGQM?editors=1000

我必须如何处理我的代码才能获得所需的结果?


更新:

好的。所以,一个新的代码。我能够解决我最初遇到的一些问题,通过使用+ i而不是#{i}.

其次,通过向block我的 Pug mixin 添加标签,我能够包含链接,没有问题。

这是新代码:

- var data=[{'title':'Home Run', 'button':'It\'s a win'}, {'title':'Testing', 'button':'Tested'}, {'title':'Foreground', 'button':'Background'}, {'title':'Forest', 'button':'Trees'}]


mixin list(title)
  h2= title
  block

.slide-container
  each item in data
    //- - var i = 0;
    //-   while i < 4
    section(class='slide-' + i++)
      +list(item.title)
        a(href='#')= item.button

呈现:

<div class="slide-container">
  <section class="slide-NaN">
    <h2>Home Run</h2><a href="#">It's a win</a>
  </section>
  <section class="slide-NaN">
    <h2>Testing</h2><a href="#">Tested</a>
  </section>
  <section class="slide-NaN">
    <h2>Foreground</h2><a href="#">Background</a>
  </section>
  <section class="slide-NaN">
    <h2>Forest</h2><a href="#">Trees</a>
  </section>
</div>

所以,剩下的唯一事情就是让类在编译时正确迭代。我已经得到了style-0,style-5和现在的一些结果style-NaN的一些结果。

我现在怎样才能让它像style-1,style-2等一样工作?

4

1 回答 1

1

回答您的第一个问题: Pug不再支持属性插值(如class='slide-#{i}') 。尝试做,而不是。class='slide-' + i

关于第二个问题:你有两个独立的循环,这就是为什么按钮和标题是分开的。如果您希望它们出现在相同的section容器中,您需要以某种方式将两者放在一个循环中,以便一次迭代添加两者。

关于你的第三个问题:我不完全确定我理解了这个问题,但这是我将如何解决它的一支笔:

.slide-container
  each item, i in data
    section(class='slide-' + (i + 1))
      +list(item.title)
        a(href='#')= item.button
于 2017-12-27T08:23:57.577 回答