簡體   English   中英

在每個循環內的給定迭代中在Handlebarsjs中推送html標記

[英]Pushing an html tag in Handlebarsjs at a given iteration within an each loop

我的channel.json有7個信息對象在hb中迭代,我想在它們之間推送一個日期。 換句話說,如何在第3次迭代后使用把手在循環之間推送html標簽? 最終我想推進一個循環。 我想通過修改.json數據來實現這一目標。

我的index.handlebars中有以下代碼。

 <div class="container">
      <h5>{{msg}}</h5>
      {{#each channelData}}
      <div class="card-panel grey lighten-5 z-depth-1">
        <div class="row valign-wrapper">
          <div class="col s1">
            <img alt="" class="circle responsive-img align" src="{{subjectPhotoUrl}}">
          </div>
          <div class="col s5">
            <div>
              <h5 class="title">{{title}}</h5>
              <br/>
              <p class="description">{{description}}</p>
            </div>
          </div>
          <div class="col s3">
            <div class="align">
              <img alt="" class="circle responsive-img" src=
              "{{instructorPhotoUrl}}"> <span class="instructor">{{instructorName}}</span>
            </div>
           </div> {{/each}}

以下代碼位於我的app.js文件中。

   var channel  = require("./data/channel.json");
    app.get('/', function(req, res) {
        res.render('index', {
        msg:new Date(),
        channelData: channel
      });
    });

我還想知道是否有可能操縱元素讓7個容器中的2個靠近在一起,0邊距和紅色背景? 意味着只為兩個容器操作css,其中一個尚未創建,並仍在迭代它們。

另外,我如何能夠讓{{msg}}顯示在循環內部,目前如果我添加{{msg}}標簽代替{{title}}標簽沒有顯示任何內容,但它確實顯示在外面在循環之上。

您可以利用循環內的事實@index引用當前索引,並定義自定義塊幫助程序以根據其值有條件地呈現標記。

當然,雖然你可以用把手做到這一點,但這違背了它的理念,在函數中放置任何邏輯格式化傳遞給模板的數據會更加慣用。

助手可能看起來像:

Handlebars.registerHelper('nthIteration', function(index, i, options) {
    if (index === i) {
        return options.fn(this);
    }
    return options.inverse(this);
});

你會像這樣使用它:

{{#each channelData}}
    <!-- my regular markup -->
    <div class="card-panel grey lighten-5 z-depth-1">
    </div>
    {{#nthIteration @index 2}}
        <!-- markup to insert after third iteration -->
        {{ ../msg }}
    {{/nthIteration}}
{{/each}}

我不太清楚你在第二個問題中究竟想要什么,但你可以根據自己的需要調整nthIteration塊助手。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM