从TWIG模板访问会话 [英] Accessing session from TWIG template

查看:81
本文介绍了从TWIG模板访问会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上搜索了很多有关如何从TWIG模板访问全局$_SESSION数组的方法,并发现了以下内容:{{app.session.get('index')}},但是当我调用它时,它返回一个空字符串.我有一个$_SESSION['filter']['accounts'],调用{{app.session.get('filter').accounts}}:Item "accounts" for "" does not exist时出现此错误.我在做什么错了?

解决方案

{{app.session}}引用Session对象而不是$_SESSION数组.我不认为$_SESSION数组是可访问的,除非您将其显式传递给每个Twig模板或进行扩展使其可用.

Symfony2是面向对象的,因此您应该使用Session对象设置会话属性,而不要依赖数组. Session对象将把这些东西从您那里提取出来,因此,例如,将会话存储在数据库中会更容易,因为对您而言隐藏了存储会话变量.

因此,请在会话中设置属性,并使用Session对象在树枝模板中检索值.

// In a controller
$session = $this->get('session');
$session->set('filter', array(
    'accounts' => 'value',
));

// In Twig
{% set filter = app.session.get('filter') %}
{% set account-filter = filter['accounts'] %}

希望这会有所帮助.

此致,
马特

I've searched a lot on the net how to access the global $_SESSION array from TWIG template and found this: {{app.session.get('index')}}, but when I'm calling it, it returns an empty string. I have a $_SESSION['filter']['accounts'] and I'm getting this error when calling {{app.session.get('filter').accounts}}: Item "accounts" for "" does not exist. What I'm doing wrong?

解决方案

{{app.session}} refers to the Session object and not the $_SESSION array. I don't think the $_SESSION array is accessible unless you explicitly pass it to every Twig template or if you do an extension that makes it available.

Symfony2 is object-oriented, so you should use the Session object to set session attributes and not rely on the array. The Session object will abstract this stuff away from you so it is easier to, say, store the session in a database because storing the session variable is hidden from you.

So, set your attribute in the session and retrieve the value in your twig template by using the Session object.

// In a controller
$session = $this->get('session');
$session->set('filter', array(
    'accounts' => 'value',
));

// In Twig
{% set filter = app.session.get('filter') %}
{% set account-filter = filter['accounts'] %}

Hope this helps.

Regards,
Matt

这篇关于从TWIG模板访问会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆