【问题标题】:Symfony 4: Multiple inclusion of a fileSymfony 4:文件的多次包含
【发布时间】:2018-02-17 14:38:48
【问题描述】:

这是我的base.html.twig

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{% include 'flashes/page-title.html.twig' %}</title>
</head>
    <body>
        <h1>{% include 'flashes/page-title.html.twig' %}</h1>
    </body>
</html>

我想知道为什么 twig 只包含一次这个文件?

【问题讨论】:

  • 你得到什么结果?为我工作:twigfiddle.com/s540oy
  • 只包含一个,绝不会同时包含两个。我的page-title.html.twig 包含{% for title in app.flashes('title') %}{{ title }}{% endfor %}

标签: include twig symfony4


【解决方案1】:

当您从 flashbag 中收到一条 flash 消息时,该消息会同时被清除。您可以在 Symfony's documentation of flash messagesFlashBagInterface API 中看到这一点。

所以我的猜测是 Twig 两次包含该文件,但第二次 flashbag 只是空的。这就是为什么h1 标签没有得到任何东西的原因。您可以通过在 flashes/page-title.html.twig 文件中添加一些静态内容(例如简单地 Hello world)来确认这一点,并查看该文件是否被包含两次。

您可以改为使用peek() 方法来检索消息,同时将其保存在包中,即如果前者不起作用,则使用{% for title in app.flashes.peek('title') %}{% for title in app.session.flashbag.peek('title') %} 之类的方法。但随后消息不会被清除。在您的情况下,这可能是问题,也可能不是问题。

在这种情况下,除了 Flash 消息之外,还有其他更好的方法吗?

【讨论】:

  • 你没事!鉴于此,app.session.flashbag.peek('title') 似乎返回了一个数组。我认为 flash 是一个实用的解决方案,但在我找到最好的方法之前,我会回到我之前有效的逻辑!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-11
  • 1970-01-01
  • 1970-01-01
  • 2021-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多