【问题标题】:Embedding Symfony controllers from other bundles嵌入来自其他包的 Symfony 控制器
【发布时间】:2014-10-22 19:16:20
【问题描述】:

这似乎是一个有趣的问题,我不确定我是否遗漏了什么,因为它应该很简单,但事实并非如此。

场景

  1. 我有一个名为 AcmePageBundle 的包
  2. 另一个包名为AcmeGalleryBundle
  3. 我想将load an embedded view from the controller 使用AcmeGalleryBundle 捆绑到AcmePageBundle 上的模板文件中

代码

AcmeGalleryBundle\Controller\DisplayController.php

class DisplayController extends Controller
{
    public function embedAction($galleryId)
    {
        $gallery = $this->getDoctrine()->getRepository('AcmeGalleryBundle')->find($galleryId);
        if (!$gallery) {
            throw $this->createNotFoundException('Gallery could not be found');
        }

        return $this->render('AcmeGalleryBundle:Display:embed.html.twig', array(
            'gallery' => $gallery,
        ));
    }
}

AcmeGalleryBundle\Resources\views\Display\embed.html.twig

  <div class="gallery">
  {% for photo in gallery.photos %}
    <a href="{{ photo.webPath }}" rel="shadowbox[gallery];">
      <img src="{{ photo.webPath }}" height="100" width="100">
    </a>
  {% endfor %}
  </div>

AcmePageBundle\Resources\views\Default\index.html.twig

{# ... extra HTML content #}
  <h2>Gallery</h2>
  {{ render(controller('AcmeGalleryBundle:Display:embed', {
      'galleryId': 123
  })) }}
{# rest of the HTML content #}

错误

当尝试渲染使用 AcmePageBundle:Default:index.html.twig 的页面时,我得到了

在 AcmePageBundle:Default:index.html.twig 的第 18 行渲染模板(“类 'AcmeGalleryBundle' 不存在”)期间引发了异常。

当然,AcmeGalleryBundle 确实存在。我怀疑我在某个地方遗漏了一个范围问题。

疑难解答

  1. 确保AcmeGalleryBundle 加载到AppKernel.php 文件中
  2. 尝试将use Acme\GalleryBundle 添加到AcmePageBundle.php 捆绑文件的顶部。
  3. Found an issue on GitHub relating to the problem with no response from the devs yet.我已经添加了自己的 cmets - 这实际上可能是一个错误。

我错过了什么明显的东西吗?

【问题讨论】:

    标签: php symfony twig


    【解决方案1】:

    我的错误在这一行:

    $gallery = $this->getDoctrine()->getRepository('AcmeGalleryBundle')->find($galleryId);
    

    命令getRepository('AcmeGalleryBundle') 需要包含我尝试加载相关存储库的实体。正确的代码是:

    $gallery = $this->getDoctrine()->getRepository('AcmeGalleryBundle:Gallery')->find($galleryId);
    

    我错误地认为这是render(controller(...)) 功能的问题。修复后,一切正常。下次我应该仔细查看我的堆栈跟踪!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      相关资源
      最近更新 更多