CodeIgniter How to access session variables in twig templates CodeIgniter How to access session variables in twig templates codeigniter codeigniter

CodeIgniter How to access session variables in twig templates


To add the session variable on your twig template, you have to add the following line in your Twig library or controller.

$datasession = array(    'nick' => $sess_nick,    'login_ok' => true);$this->session->set_userdata($datasession);$this->_twig->addGlobal("session", $this->CI->session);

Then on your twig template, you can print the session like this

{{ session.userdata.nick }}

Since in CodeIgniter, the session stored by user is usually in the userdata array. Otherwise, you can just simply call the session variable and name

{{ session.nick }}

Src: http://llanalewis.blogspot.co.uk/2013/08/codeigniter-add-session-in-twig.html


Ok, thanks to Latheesan Kanes for your help. It was so much helpful your guideness. I want to share the way I solved this problem.

As Latheesan mentioned we have to use the addGlobal() method (I added this method in my Twig library folder)

like following:

$this->_twig->addGlobal("session", $this->CI->session);

But don't forget before to load the Session library. This way.

$this->CI->load->library('session');

This way you can have your session globally in all your twig views.


I'm using CodeIgniter 3RC3 and the Twig-Codeigniter library (thanks Erik & Bennet!).

To enable easy session access in twig, I added one line to the /application/libraries/Twig.php file's __construct() method:

public function __construct(){    $this->_ci = & get_instance();    $this->_ci->config->load(self::TWIG_CONFIG_FILE); // load config file    // set include path for twig    ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . APPPATH . 'third_party/Twig/lib/Twig');    require_once (string)'Autoloader.php';    // register autoloader    Twig_Autoloader::register();    log_message('debug', 'twig autoloader loaded');    // init paths    $this->template_dir = $this->_ci->config->item('template_dir');    $this->cache_dir = $this->_ci->config->item('cache_dir');    // load environment    $loader = new Twig_Loader_Filesystem($this->template_dir, $this->cache_dir);    $this->_twig_env = new Twig_Environment($loader, array(                                            'cache' => $this->cache_dir,                                            'auto_reload' => TRUE));    // ADD SESSION TO TWIG - JZ    $this->_twig_env->addGlobal('session', $this->_ci->session);    // SESSION IS NOW AVAILABLE IN TWIG TEMPLATES!    $this->ci_function_init();}

Now that we have our session loaded into our twig instance, we access session variables (such as CI's userdata) in our twig templates like so:

<span>__ci_last_regenerate: {{ session.userdata.__ci_last_regenerate }}</span>