doushi5117 2013-03-30 15:29
浏览 48
已采纳

在Symfony 2.2中无法使用Twig访问对象属性值

I cannot access the objects properties using the Twig dot notation. For example, from looking at the object dump, I should be able to do image.copyright, which should print "Blue button near the Cayman Islands, Caribbean (© Lawson Wood/Aurora Photos)" for the first item.

The error message I get is

Method "copyright" for object "SimpleXMLElement" does not exist in ARRaiDesignBundle:Default:wallpapers.html.twig at line 12

While dumping the object using dump(image) dumps each of the objects.

Controller class:

$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 file:

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

Object dump using dump(image) in Twig:

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"
...

Can anyone suggest how to do this? I know I can use PHP rendering instead of Twig, but that's not a fix for me. Thanks.

  • 写回答

4条回答 默认 最新

  • duanbage2161 2013-03-30 19:14
    关注

    This was happening due to Bing's werid XML structure, the last bit is not iterative friendly. With standard PHP it's fine, but with Twig, it doesn't catch the errors for the last element.

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

    To fix this, I just unset tooltips. "unset($xml->tooltips)"

    Thanks @JaredFarrish for providing clean xml. :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址