2016-05-24 6 views
1

@eachブレード・ディレクティブを使用して、一連の問合せ結果をループしてレンダリングします(この場合、@ eachディレクティブはforeachクエリーの結果に応じてレンダリングされるHTMLが変更されます)。これはうまくいきますが、クエリ自体の現在のインデックスを取得しようとする問題があります。Laravel - @each現在の反復を取得する

つまり、@ eachディレクティブを使用して、レンダリングされている部分の現在のループのキー(またはインデックス)にアクセスできる必要があります。

あなたが知る必要があるものがあれば、尋ねてください。

ありがとうございます! @eachディレクティブのために実行のソースコードを見てみると

答えて

3

には、次のものが得られます。

を照らし\ビュー\ Factory.php

/** 
* Get the rendered contents of a partial from a loop. 
* 
* @param string $view 
* @param array $data 
* @param string $iterator 
* @param string $empty 
* @return string 
*/ 
public function renderEach($view, $data, $iterator, $empty = 'raw|') 
{ 
    $result = ''; 

    // If is actually data in the array, we will loop through the data and append 
    // an instance of the partial view to the final result HTML passing in the 
    // iterated value of this data array, allowing the views to access them. 
    if (count($data) > 0) { 
     foreach ($data as $key => $value) { 
      $data = ['key' => $key, $iterator => $value]; 

      $result .= $this->make($view, $data)->render(); 
     } 
    } 

    // If there is no data in the array, we will render the contents of the empty 
    // view. Alternatively, the "empty view" could be a raw string that begins 
    // with "raw|" for convenience and to let this know that it is a string. 
    else { 
     if (Str::startsWith($empty, 'raw|')) { 
      $result = substr($empty, 4); 
     } else { 
      $result = $this->make($empty)->render(); 
     } 
    } 

    return $result; 
} 

あなたはこれらのラインに気付いた場合:

$data = ['key' => $key, $iterator => $value]; 

$result .= $this->make($view, $data)->render(); 

$keyという変数が自動的にレンダリングビューに渡されます。これには配列ループの現在のインデックスが含まれているはずです。

+0

ありがとうございました。 – mattrick

関連する問題