dongqu3623 2014-04-16 16:03
浏览 41
已采纳

迭代控制器和树枝中的对象

I am struggling on how to display an array of objects in my twig symfony2 web services. Can you please help me, as I got an Error code. My problem is that I cannot display the objects arrays in my twig. this is my code:

CONTROLLER:

public function InfoAction($id)
    {
        $client = new Client('https://www.googleapis.com/books/v1');
        $request = $client->get('volumes?q=id='.$id);
        $response =  $request->send();
        $content = $response->json();
        var_dump($content);
        return $this->render('BooksBookBundle:GoogleBooks:Info.html.twig', array (
          ['items' => $content['items']],
          ['books' => $content, array(
          new volumeInfo('title', 'authors','publisher'),
          new SaleInfo('country','saleability'))]
             ));

}

Json strings I want to display:

{
 "kind": "books#volume",
 "id": "8Pr_kLFxciYC",
 "etag": "Eyx8QAfP36s",
 "selfLink": "https://www.googleapis.com/books/v1/volumes/8Pr_kLFxciYC",
 "volumeInfo": {
  "title": "Flowers For Algernon",
  "authors": [
   "Daniel Keyes"
  ],
  "publisher": "Hachette UK",
  "publishedDate": "2012-11-15",
  "description": "Charlie Gordon, IQ 68, is a floor sweeper, and the gentle butt of everyone's jokes, until an experiment in the enhancement of human intelligence turns him into a genius. But then Algernon, the mouse whose triumphal experimental tranformation preceded his, fades and dies, and Charlie has to face the possibility that his salvation was only temporary.",
  "industryIdentifiers": [
   {
    "type": "ISBN_10",
    "identifier": "0575088494"
   },
   {
    "type": "ISBN_13",
    "identifier": "9780575088498"
   }
  ],
  "pageCount": 224,
  "printedPageCount": 328,
  "printType": "BOOK",
  "categories": [
   "Fiction / Science Fiction / General"
  ],
  "averageRating": 4.0,
  "ratingsCount": 3081,
  "contentVersion": "0.1.1.0.preview.2",
  "imageLinks": {
   "smallThumbnail": "http://bks7.books.google.co.uk/books?id=8Pr_kLFxciYC&printsec=frontcover&img=1&zoom=5&edge=curl&imgtk=AFLRE71wn80lT4uw3t25Ft3G1PFmGSb21z4aL4ZZDTl9dvDTlCKqKQFCDikPUeFgK6yg9jexlnalsIONz423vhBma2-ywTG9PdQKaCS85Q6RTtdVVORaswE&source=gbs_api",
   "thumbnail": "http://bks7.books.google.co.uk/books?id=8Pr_kLFxciYC&printsec=frontcover&img=1&zoom=1&edge=curl&imgtk=AFLRE73tDFRwijQ8sfAvU6Zv0jLLX1jXqdYaNWsensdQhfrU32cpemYTpAT25gE_ocYLTK9z5sW6UOBadpWTCR5ay1wTvXjjRRHIpjh6hCeKAibbIWe2wG8&source=gbs_api",
   "small": "http://bks7.books.google.co.uk/books?id=8Pr_kLFxciYC&printsec=frontcover&img=1&zoom=2&edge=curl&imgtk=AFLRE73T-jlqTcANz-XTotRx99HlpFSDOInRp6nxzUzQskstY09icPjU9lZIrBwLFt3sexPUSxITpgTldQB10xyJbplEMHCDqa9vbN16xXSgxRtUlSsIdYw&source=gbs_api"
  },
  "language": "en",
  "previewLink": "http://books.google.co.uk/books?id=8Pr_kLFxciYC&hl=&source=gbs_api",
  "infoLink": "http://books.google.co.uk/books?id=8Pr_kLFxciYC&hl=&source=gbs_api",
  "canonicalVolumeLink": "http://books.google.co.uk/books/about/Flowers_For_Algernon.html?hl=&id=8Pr_kLFxciYC"
 },
 "layerInfo": {
  "layers": [
   {
    "layerId": "geo",
    "volumeAnnotationsVersion": "4"
   }
  ]
 },
 "saleInfo": {
  "country": "GB",
  "saleability": "FOR_SALE",
  "isEbook": true,
  "listPrice": {
   "amount": 4.99,
   "currencyCode": "GBP"
  },
  "retailPrice": {
   "amount": 3.99,
   "currencyCode": "GBP"
  },
  "buyLink": "http://books.google.co.uk/books?id=8Pr_kLFxciYC&hl=&buy=&source=gbs_api",
  "offers": [
   {
    "finskyOfferType": 1,
    "listPrice": {
     "amountInMicros": 4990000.0,
     "currencyCode": "GBP"
    },
    "retailPrice": {
     "amountInMicros": 3990000.0,
     "currencyCode": "GBP"
    }
   }
  ]
 },
 "accessInfo": {
  "country": "GB",
  "viewability": "PARTIAL",
  "embeddable": true,
  "publicDomain": false,
  "textToSpeechPermission": "ALLOWED_FOR_ACCESSIBILITY",
  "epub": {
   "isAvailable": true,
   "acsTokenLink": "http://books.google.co.uk/books/download/Flowers_For_Algernon-sample-epub.acsm?id=8Pr_kLFxciYC&format=epub&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
  },
  "pdf": {
   "isAvailable": false
  },
  "webReaderLink": "http://books.google.co.uk/books/reader?id=8Pr_kLFxciYC&hl=&printsec=frontcover&output=reader&source=gbs_api",
  "accessViewStatus": "SAMPLE",
  "quoteSharingAllowed": false
 }
}

MY TWIG

{% extends "::base.html.twig" %}

{% block title %}BooksBookBundle:GoogleBooks:volumes{% endblock %}

{% block body %}
    <h1>Book Information</h1>
   {% for volumeInfo in volumeInfos %}
    {{ volumeInfo.title }}
       {% endfor %}
{% endblock %}

my var_dump

array (size=3)
  'kind' => string 'books#volumes' (length=13)
  'totalItems' => int 1
  'items' => 
    array (size=1)
      0 => 
        array (size=8)
          'kind' => string 'books#volume' (length=12)
          'id' => string '8Pr_kLFxciYC' (length=12)
          'etag' => string 'KEN5W2AmaSo' (length=11)
          'selfLink' => string 'https://www.googleapis.com/books/v1/volumes/8Pr_kLFxciYC' (length=56)
          'volumeInfo' => 
            array (size=17)
              ...
          'saleInfo' => 
            array (size=7)
              ...
          'accessInfo' => 
            array (size=10)
              ...
          'searchInfo' => 
            array (size=1)

error message:

ClassNotFoundException: Attempted to load class "volumeInfo" from namespace "Books\BookBundle\Controller" in /Users/prezequias/Desktop/santosbookreview/src/Books/BookBundle/Controller/GoogleBooksController.php line 31. Do you need to "use" it from another namespace?

the variable books was created by me, maybe I am wrong.

Thanks for your help in advance

  • 写回答

2条回答 默认 最新

  • duanguan3863 2014-04-17 07:24
    关注

    You try to instantiate a PHP class VolumeInfo, but this PHP class don't exist !

    A solution :

    Controller :

    $items = $content->items;
    return $this->render('BooksBookBundle:GoogleBooks:Info.html.twig', array ('items'=>$items));
    

    Template :

    {% for item in items %}
        Title : {{ item.volumeInfo.title }}<br>
        Author : 
        {% for author in item.volumeInfo.authors %}
           {{ item.volumeInfo.authors[0] }}
        {% endfor %}
    {% endfor %}
    

    Or, if you always have 1 book, you can pass directly the book to the template:

    Controller :

    $items = $content->items[0];
    return $this->render('BooksBookBundle:GoogleBooks:Info.html.twig', array ('item'=>$item));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择