簡體   English   中英

Twig沒有在對象中顯示數據

[英]Twig doesn't show data in object

我正在嘗試使用Twig顯示Doctrine 2實體對象的簡單列表。 使用DQL查詢的原始結果獲取對象。 PHP代碼如下:

/*
 * I know the query in the Repository class works as I get the correct objects
 * from the method and can iterate through them with foreach in PHP, displaying
 * data from the object through getters, like ->getId()
 */
$received = $repo->getReceived($id);

/*
 * This appears to work, the variables are assigned correctly.
 */
echo $template->render(array("received" => $received, "first" => $received[0]));

Twig模板包含以下內容:

{% for item in received %}
    <li>Item: {{ item.id }}, {{ first.id }}</li>
{% endfor %}

奇怪的是,細枝正確地循環訪問了接收到的數組,數組中有三個對象,並且輸出了三行,但是當作為item.id訪問時,id(或任何其他成員)沒有出現,但是第二個輸出,first.id,正確顯示。

我應該看到的是:

Item 1, 1
Item 2, 1
Item 3, 1

但是我看到的是:

Item , 1
Item , 1
Item , 1

我嘗試了各種變體來獲取輸出,但是到目前為止,item.getId,item.getId()仍然沒有任何作用。

有什么想法我在這里想念的嗎?

編輯轉儲輸出

{{dump(received)}}返回以下內容:

array(3) {
  [0]=>
  object(Received)#219 (6) {
    ["id":"Received":private]=>
    int(1)
  ... snip ...
  }
  [1]=>
  object(Received)#208 (6) {
    ["id":"Received":private]=>
    int(2)
  ... snip ...
  }
  [2]=>
  object(Received)#210 (6) {
    ["id":"Received":private]=>
    int(3)
  ... snip ...

我已將其縮減,這是三個完整的Doctrine實體對象,因此它們位於數組中,並且看起來正確。

盡管我不明白為什么需要這樣做,但我終於找到了解決方法。 我將數組更改為包含一組數組,而不是對象,但這也不起作用。

然后,我創建了另一個數組,用於測試具有完全相同的結構,並且該數組正常工作。 任何人都不知道是什么導致一個陣列工作而另一個陣列出現故障? 兩者都是二維數組。

所以我最終得到的是我使用了二維數組並將樹枝代碼更改為:

{% for item in received %}
    <li>Item: {{ attribute(item, 'id') }}</li>
{% endfor %}

由於某種原因,盡管我以前曾嘗試過該屬性,但仍需要那里的attribute(),但是Twig抱怨說attribute()不存在。

希望這會對其他人有所幫助。

暫無
暫無

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

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