2013-03-30 108 views
0

我無法使用Twig點表示法訪問對象屬性。例如,從查看對象轉儲,我應該可以執行image.copyright,它應該在第一項中打印「開曼羣島附近的藍色按鈕,加勒比(©Lawson Wood/Aurora Photos)」。無法使用Symfony 2.2中的Twig訪問對象屬性值

該錯誤消息我得到的是

方法 「版權」 爲對象 「的SimpleXMLElement」 不存在ARRaiDesignBundle:默認:wallpapers.html.twig 12行

儘管傾銷對象使用轉儲(圖像)轉儲每個對象。

控制器類:

$host = 'http://www.bing.com'; 
$file = $host . '/HPImageArchive.aspx?format=xml&idx=0&n=10&mkt=en-US'; 
$xml = simplexml_load_file($file); 

return $this->render('ARRaiDesignBundle:Default:wallpapers.html.twig', array('xml' => $xml, 'host' => $host)); 

wallpapers.html.twig文件:

... 
{% for image in xml %} 
<p><pre>{{ image.copyright }}</pre></p> 
{% endfor %} 
... 

在枝杈使用dump(圖像)對象轉儲:

object(SimpleXMLElement)#268 (12) { 
    ["startdate"]=> 
    string(8) "20130330" 
    ["fullstartdate"]=> 
    string(12) "201303300000" 
    ["enddate"]=> 
    string(8) "20130331" 
    ["url"]=> 
    string(46) "/az/hprichbg/rb/BlueButton_EN-US1108621411.jpg" 
    ["urlBase"]=> 
    string(43) "/az/hprichbg/rb/BlueButton_EN-US10208337365" 
    ["copyright"]=> 
    string(77) "Blue button near the Cayman Islands, Caribbean (© Lawson Wood/Aurora Photos)" 
    ["copyrightlink"]=> 
    string(74) "http://www.bing.com/search?q=Blue+Button+%28Porpita+porpita%29&form=hpcapt" 
    ["drk"]=> 
    string(1) "1" 
    ["top"]=> 
    string(1) "1" 
    ["bot"]=> 
    string(1) "1" 
... 

任何人都可以建議如何做這個?我知道我可以使用PHP渲染而不是Twig,但這對我來說不是一個解決方法。謝謝。

+0

這裏是線在輸出該行的源代碼中:https://github.com/fabpot/Twig/blob/master/lib/Twig/Template.php#L424 –

+0

您是否嘗試過[將'$ xml'投射到'array']( http://codepad.org/s4tFbNvM)? –

+0

@JaredFarrish我使用了您提供的simplexml_load_string($ file)的數據。看來symfony不喜歡bing的xml。在內也有。這是一個可以迭代的結構。雖然,標準的php很好,但小枝功能並不完美。 –

回答

1

這是由於Bing的werid XML結構發生的,最後一點不是迭代友好的。使用標準PHP很好,但是使用Twig,它不會捕獲最後一個元素的錯誤。

<images> 
<image>...</image> 
<image>...</image> 
<image>...</image> 
<image>...</image> 
<image>...</image> 
<image>...</image> 
<image>...</image> 
<image>...</image> 
<tooltips>...</tooltips> 
</images> 

要解決這個問題,我只是取消設置提示。 「unset($ xml-> tooltips)」

感謝@JaredFarrish提供乾淨的xml。 :)

1

在我看來,你的SimpleXMLElement沒有實施神奇的方法。當您撥打Twig object.property時,它會調用您的objectgetProperty()方法。嘗試直接在樹枝上訪問屬性:

{{ image['copyright'] }} 
+0

我已經嘗試過了,不起作用:類型爲「SimpleXMLElement」的對象(帶有ArrayAccess)中的鍵「版權」不存在於ARRaiDesignBundle:默認值:第12行的wallpapers.html.twig中 –

+1

可能是您的一個對象沒有這樣的財產?你有沒有嘗試用'default'過濾器迭代它? '{{image ['copyright'] | default('')}}' –

+0

@AmarjeetSinghRai否則,您可以嘗試從使用樹枝的循環中轉儲每個對象並查看可訪問的屬性 - '{{dump(image)}}'' –

0

我相信你必須代理該對象。創建一個包裝SimpleXMLElement對象並定義getCopyright()方法的新對象。

class Element 
{ 
    protected $xmlElement; 
    public function getCopyright() 
    { 
     return $this->xmlElement->copyright; 
    } 
}