从 Twig 访问 Cookie? [英] Access Cookies from Twig?

查看:24
本文介绍了从 Twig 访问 Cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

解决方案

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 }}

这篇关于从 Twig 访问 Cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆