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

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

问题描述

我在基本控制器中有这样的代码:

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,
));

然后在Base Twig中,我使用此变量来做各种事情。
是否可以从Twig访问$ this-> eu_cookie_preference变量,而不必在每个控制器函数中将其显式传递给每个Twig?

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.

推荐答案

答案



您可以使用Twigs addGlobal 函数执行此操作。 请参阅手册

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]);
    }
}

并传递如下值:

$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访问Cookies?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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