首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法使用Symfony 2.2中的Twig访问对象属性值

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

Stack Overflow用户
提问于 2013-03-30 15:29:41
回答 4查看 10K关注 0票数 0

我不能使用Twig点表示法访问对象属性。例如,从对象转储的角度来看,我应该能够做image.copyright,它应该为第一项打印“在开曼群岛附近的蓝色按钮,加勒比((C) Lawson Wood/Aurora Photos)”。

我得到的错误信息是

对象"SimpleXMLElement“的”版权“方法在第12行的ARRaiDesignBundle:Default:wallpapers.html.twig中不存在

使用转储(映像)转储对象时,转储每个对象。

控制器类:

代码语言:javascript
复制
$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文件:

代码语言:javascript
复制
...
{% for image in xml %}
<p><pre>{{ image.copyright }}</pre></p>
{% endfor %}
...

使用Twig中的转储(图像)转储对象:

代码语言:javascript
复制
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,但这对我来说不是一个解决办法。谢谢。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-03-30 19:14:56

这是因为Bing的werid XML结构,最后一点并不是迭代友好的。对于标准PHP来说,这很好,但是对于Twig,它不会捕捉到最后一个元素的错误。

代码语言:javascript
复制
<images>
<image>...</image>
<image>...</image>
<image>...</image>
<image>...</image>
<image>...</image>
<image>...</image>
<image>...</image>
<image>...</image>
<tooltips>...</tooltips>
</images>

为了解决这个问题,我只是取消了工具提示。“unset($xml->工具提示)”

感谢@JaredFarrish提供了干净的xml。:)

票数 1
EN

Stack Overflow用户

发布于 2014-01-16 10:52:12

使用示例php http://www.php.net/manual/fr/simplexml.examples-basic.php

在细枝中,要从“评级”项中获取属性“type”,请使用属性(="@ attributes ")如下:

代码语言:javascript
复制
{% for rating in movies.movie.rating %}
   {{ rating.attributes.type }}
{% endfor %}
票数 3
EN

Stack Overflow用户

发布于 2013-03-30 16:00:46

在我看来,您的SimpleXMLElement似乎没有实现神奇的方法。当您调用Twig object.property时,它调用objectgetProperty()方法。尝试在Twig中直接访问属性:

代码语言:javascript
复制
{{ image['copyright'] }}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15720201

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档