简体   繁体   English

使用 Twig 模板访问 cookie 值

[英]Access cookie value with Twig template

After user submit login form and if checkbox "Remember me" is clicked, username will be stored in cookie variable.用户提交登录表单后,如果单击“记住我”复选框,用户名将存储在 cookie 变量中。 After that when user tries to login again, his username should appear in username field of login form.之后,当用户再次尝试登录时,他的用户名应出现在登录表单的用户名字段中。 But I cant get the cookie value with Twig template.但是我无法使用 Twig 模板获取 cookie 值。 Cookie exists in $_COOKIE superglobal variable, but I dont know how to access it via twig template. Cookie 存在于 $_COOKIE 超全局变量中,但我不知道如何通过 twig 模板访问它。

Tried to access it with this piece of code below but it doesnt work.尝试使用下面的这段代码访问它,但它不起作用。

{% if app.request.cookies.has('remember_me') %}
  {{app.request.cookies.get('remember_me')}}
{% endif %}

I believe this Answer will solve your problem.我相信这个答案会解决你的问题。

You can use Twigs addGlobal function to do so.您可以使用addGlobal函数来执行此操作。 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 just add a Global named cookies and set it to $_COOKIE .您只需添加一个名为 Global 的cookies并将其设置为$_COOKIE You now can access cookies by calling the cookies variable from inside twig.您现在可以通过从 twig 内部调用 cookies 变量来访问 cookies。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM