从 TWIG 模板访问会话 [英] Accessing session from TWIG template
问题描述
我在网上搜索了很多如何从 TWIG 模板访问全局 $_SESSION
数组,发现这个:{{app.session.get('index')}}
,但是当我调用它时,它返回一个空字符串.我有一个 $_SESSION['filter']['accounts']
并且在调用 {{app.session.get('filter').accounts}} 时出现这个错误
:"的项目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}}
指的是 Session
对象而不是 $_SESSION
数组.我不认为 $_SESSION
数组是可访问的,除非你明确地将它传递给每个 Twig 模板,或者你做了一个使它可用的扩展.
{{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 是面向对象的,所以你应该使用 Session
对象来设置会话属性而不是依赖数组.Session
对象会将这些东西从您身上抽象出来,因此更容易将会话存储在数据库中,因为存储会话变量对您来说是隐藏的.
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.
因此,在会话中设置您的属性并使用 Session
对象在树枝模板中检索值.
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'] %}
希望这会有所帮助.
问候,
马特
这篇关于从 TWIG 模板访问会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!