【问题标题】:How can I get access to service variables?如何访问服务变量?
【发布时间】:2019-03-05 11:31:02
【问题描述】:
public function pages($slug, PagesGenerator $pagesGenerator)
{
    $output = $pagesGenerator->getPages($slug);

    $id = $page->getId();

    return $this->render('list.html.twig', [ 'output' => $output,  'id' => $id]);
}

但我得到了错误:

注意:未定义变量:页面

【问题讨论】:

  • 不应该是$output['page']->getId()吗?

标签: php symfony scope


【解决方案1】:
public function pages($slug, PagesGenerator $pagesGenerator)
{
    $output = $pagesGenerator->getPages($slug);

    // here is your error: $page is not defined.
    $id = $page->getId();

    // something like this?
    $id = $output['page']->getId();

    return $this->render('list.html.twig', [ 'output' => $output,  'id' => $id]);
}

【讨论】:

    【解决方案2】:

    你的新控制器显然没有template变量进入变量列表,只有output。看起来您的正确代码应该是:

      public function pages($slug, PagesGenerator $pagesGenerator)
      {
          $output = $pagesGenerator->getPages($slug);
    
          return $this->render('list.html.twig', $output);
      }
    

    更新:更新问题的答案基本相同,您需要做的就是将模板变量作为普通数组传递

    return $this->render('list.html.twig', array_merge($output, ['table' => $table]));
    

    或根据模板中的实际结构使用它们,例如{{ output.page }} 而不是 {{ page }}

    【讨论】:

    • 谢谢。我更新了我的问题以向您展示,我的情况有点困难。我还希望能够在控制器内部访问“页面”
    • 所以我仍然收到错误消息Notice: Undefined variable: page
    • @Jarla 我已经更新了答案,但在答案发布后更改问题并不是一个好习惯。考虑从一开始就发布正确的问题
    • 是的,对不起。才发现,更新更清晰了
    猜你喜欢
    • 2016-08-24
    • 2017-04-03
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多