【问题标题】:symfony3 twig and show session arraysymfony3 twig 和显示会话数组
【发布时间】:2016-11-25 12:11:17
【问题描述】:

我在会话中有数组,但我无法显示它们。 我的代码: 控制器:

  $game = $request->query->get('game');
  $type = $request->query->get('type');
  $odd = $request->query->get('odd');

  $kupon = array(
                 'game' => $game,
                 'type' => $type,
                 'odd' => $odd,
               );

   $this->get('session')->set('kupon', $kupon);

其中 'game' 是例如:'Arsenal - Chelsea','type' 是像 1 这样的数字,奇数是像 '2.2' 这样的浮点数。

树枝文件:

{% if app.session.get('kupon') is not null %}
<table>
{% for kupon in session %}
    <tr>
      <td>{{ kupon.game }}</td>
      <td>{{ kupon.type }}</td>
      <td> </td>
    </tr>
{% endfor %}
</table>

一切正常,但是当我尝试登录并显示数据会话时,出现以下错误:

无法访问 baw\kupon.html.twig 第 13 行中字符串变量(“PNdjNUeuZ_d5uJlm1VG7zPZhp2Vb4CY3nDf93vAQ574”)的属性(“游戏”)。

这个变量来自登录后的会话,我检查了关于它的转储信息:

array(3) { 
["_csrf/login"]=> string(43) "PNdjNUeuZ_d5uJlm1VG7zPZhp2Vb4CY3nDf93vAQ574" ["login"]=> string(4) "test" 
["kupon"]=> array(3) { ["game"]=> string(31) "Arsenal Londyn - Chelsea Londyn" ["type"]=> string(1) "1" ["odd"]=> string(3) "2.2" } }

现在我没有任何想法来解决这个问题。

【问题讨论】:

  • 那么您使用的是 symfony2 还是 3?请使用正确的标签...

标签: php session twig symfony


【解决方案1】:

{% for kupon in session %} 不会循环覆盖app.session.get('kupon')

你想做的是:

{% for kupon in app.session.get('kupon') %}

但是看着你转储的数据,app.session.get('kupon') 只是一个数据集,所以你甚至不能循环它(得到想要的结果)......

只是:

{{ app.session.get('kupon').game }}

关于你的数据的额外解释:你在你的会话中有这个:

"kupon" => [
    "game" => ...
    "type" => ...
    ...
]

为了能够循环这些,您需要收集您的数据类型:

"kupon" => [
    [
        "game" => ...
        "type" => ...
        ...
    ],
    [
        "game" => ...
        "type" => ...
        ...
    ],
    ....
]

【讨论】:

  • 好的,我改变了它,但现在一切都是 x3。我必须单独拥有带有数组的所有数据,例如:&lt;td&gt;name&lt;/td&gt;&lt;td&gt;surname&lt;/td&gt;,现在我有类似的东西:&lt;td&gt;name surname&lt;/td&gt; &lt;td&gt;name surname&lt;/td&gt;。我改成这个:{% for kupon in app.session.get('kupon') %} 和这个:&lt;td&gt;{{ app.session.get('kupon').game }}&lt;/td&gt;。我什至尝试了kupon.game 或其他东西,但我遇到了错误:"Impossible to access an attribute ("game") on a string variable ("Arsenal Londyn - Chelsea Londyn") in baw\kupon.html.twig at第 13 行。”
  • 你试过{{ app.session.get('kupon').game }}吗?
  • 正如我所说,你不能把它放在一个循环中,因为数据不是一个集合......你只有一个“kupon”的“实例”;我已经用一个清晰​​的例子更新了我的答案
【解决方案2】:

试试下面

{% if app.session.get('kupon') is not null %}
  {% set kupon = app.session.get('kupon') %}
  <table>
      <tr>
        <td>{{ kupon.game }}</td>
        <td>{{ kupon.type }}</td>
        <td> </td>
      </tr>
  </table>
{% endif %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多