Access Cookies from Twig?

2019-06-14 03:31发布

I have code like this in the base controller:

$this->eu_cookie_preference = $this->input->cookie('eu-cookie-preference');

and in each one of my controller functions I pass this variable to the twig like this:

$this->twig->display('account/my_details.twig', array(
    'title' => 'Website | My Details',
    'lang' => $this->lang,
    'eu_cookie_preference' => $this->eu_cookie_preference,
));

And in the Base Twig I use this variable to do various things. Is there a way to access the $this->eu_cookie_preference variable from Twig without having to explicitly pass it to each Twig in every controller function?

I have a similar problem with session vars as I have to pass them to each twig in order to access them.

1条回答
Rolldiameter
2楼-- · 2019-06-14 04:26

Answer

You can use Twigs addGlobal function to do so. See manual

// Add static text
$twig->addGlobal('text', 'Hello World');
// Add array
$twig->addGlobal('arr', array(1, 2, 3));
// Add objects
$twig->addGlobal('obj', $obj);

You can use these globals just like normal vars:

This is a Text: "{{ text }}", 
item in an array {{ arr[0] }}, 
obj value {{ obj.publicAttr }} or 
obj function {{ obj.toHTML5('<img src="" />') }}

Additional information

This way you can implement lazy loading as well. If you load sessions data from your database, that will not be used in every template it can be useful to build a class like this:

class OnDemand {
    private $cache;
    private $function;

    function __construct($function) {
        $this->function = $function;
    }

    private function cache() {
        if($this->cache == null) {
            $function = $this->function;
            $this->cache = $function();
        }
    }

    function __toString() {
        $this->cache();
        return (string) $this->cache;
    }

    function __get($key) {
        $this->cache();
        return $this->cache[$key];
    }

    function __isset($key) {   
        $this->cache();
        return isset($this->cache[$key]);
    }
}

and pass values like this:

$twig->addGlobal('aDataArray', new OnDemand(function(){
    // load database data
    $data = DB::loadData(...);
    return $data;
}));

The function will only be called, when you call the variable in twig.

{{ aDataArray.user.name }}
查看更多
登录 后发表回答