kenjis / codeigniter-ss-twig

A Simple and Secure Twig integration for CodeIgniter 3.x and 4.x
MIT License
168 stars 46 forks source link

Twig global variable doesnt work #24

Closed nzhtrtlc closed 7 years ago

nzhtrtlc commented 7 years ago

Hi im adding global variable in my login controller.

  if($user){
            $user_credentials["user_session"] = [
                "user_id" => $user->user_id,
                "fullName" => $user->name. " ".$user->surname,
                "email" => $user->email,
                "logged_in" => true
            ];
            $this->session->set_userdata($user_credentials);
            $this->twig->addGlobal('user_session',$user_credentials["user_session"]);
            redirect('dashboard');
        }

In my dashboard.twig file im calling {{ user_session.fullName}} but it doesnt work. BUT If i use addGlobal method in my dashboard i can see the fullName variable. In this case it doesnt work for another controllers, works for only dashboard. But i need to use it in every controller.

kenjis commented 7 years ago

This is not a bug in Twig or codeigniter-ss-twig. It is specification.

redirect() makes your browser request another page (in your case, dashboard). HTTP is stateless protocol. And PHP also shares nothing basically. So if you access another page, PHP don't know all variables in the previous page at all.

Twig's global also means global in a single request.

But i need to use it in every controller.

Yes.

nzhtrtlc commented 7 years ago

Thank you for your answer. Is there any way that i can define global variable for twig which is works in every request ?

kenjis commented 7 years ago

If you need one variable in all pages, for example, you can set it in your MY_Controller constructor. See https://codeigniter.com/user_guide/general/core_classes.html#extending-core-class.

nzhtrtlc commented 7 years ago

Thanks this one can solve my problem. But i think you can add this feature to project then we can reach the session with session key in twig. So we do not need to add any variable or make our own controllers.

kenjis commented 7 years ago

I intend to keep this library simple wrapper for Twig. I don't add functionality which original Twig does not have. Twig doesn't care about session.

You can extend my Twig class to add your own needs. See https://github.com/kenjis/codeigniter-ss-twig/pull/23#issuecomment-277152999.