We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Accessing session variable from volt view

I am trying to display/hide a div based on a session variable (based on whether the user is logged in or not). How can i access a session variable in volt to check if it has been set?

Thanks in advance.



5.2k
Accepted
answer
edited Jun '14

In controller:

public function someAction()
{
    $this->session->set('your_variable', 'value');
}

In view (volt syntax):

{% if session.get('your_variable') == null %} {# variable is not set #}
Print something
{% else %} {# variable is set #}
Print something else
{% endif %}

You need also set a session in your $di:

$di->set('session', function() {
    $session = new Phalcon\Session\Adapter\Files();
    if (session_status() == PHP_SESSION_NONE) {
        $session->start();
    }
    return $session;
});

In controller:

public function someAction()
{
  $this->session->set('your_variable', 'value');
}

In view (volt syntax):

{% if session.get('your_variable') == null %} {# variable is not set #}
Print something
{% else %} {# variable is set #}
Print something else
{% endif %}

You need also set a session in your $di:

$di->set('session', function() {
   $session = new Phalcon\Session\Adapter\Files();
   if (session_status() == PHP_SESSION_NONE) {
       $session->start();
   }
   return $session;
});

Thank you! this worked for me :D

You're welcome :)



5.2k

Hi, Marcin Szepczynski. Your answer was give many help to me. Thank you very much! 感谢你!