Ngoài việc lưu data vào cookie còn có một số việc khác để lưu giá trị vào cookie để bật tắt 1 chức năng. Hôm nay mình sẽ hướng dẫn các bạn thực hiện nó một cách dễ dàng.
Data sẽ lưu vào cookie có tên là user
Lưu dạng:
.ajax..online.
Mỗi key lưu vào có dạng .key. (dấu chấm + từ khóa + dấu chấm)
Khi tắt chức năng nó sẽ xóa key đó ra khỏi cookie user
Ví dụ cookie user hiện tại là: .ajax..online. khi tắt ajax nó sẽ thành .online.
Code macro:
{%macro getmenu(str,par)%}{% set user=api.r.createFromGlobals().cookies.get("user")|default("Default")%}{%if (str~"." in user and par|length < 2) or par=="on"%}on{%else%}off{%endif%}{%endmacro%}{%macro setmenu(str,par)%}{%if par is not empty%}{%set user=api.r.createFromGlobals().cookies.get('user')%}{%set msS='.'~str~'.'%}{%if par=='on'%}{%if (str~'.') in user%}{%set user=user|replace({(msS):''})|raw%}{%endif%}{%set user=user~msS%}{%elseif par=='off'%}{%set user=user|split(msS)|join('')%}{%endif%}<script type="text/javascript">document.cookie="user={{user}}; path=/; expires=Thursday, 20-May-19 00:00:00 GMT";</script><meta http-equiv="Set-Cookie" content="user={{user}}; path=/; expires=Thursday, 20-May-19 00:00:00 GMT"/>{%endif%}{%endmacro%}{%import _self as thaian2009%} {%set key1='ajax'%} {{thaian2009.setmenu(key1,api.r.get(key1))}} Trạng thái ajax hiện tại: {{thaian2009.getmenu(key1,api.r.get(key1))}}
{{thaian2009.getmenu(key1,api.r.get(key1))}} là hiện trạng thái on/off của key1='ajax'
{{thaian2009.setmenu(key1,api.r.get(key1))}} là lưu trạng thái key1 vào cookie
Nguồn: http://cobethoitiet.wap.mu
![[OFF]](/assets/images/off.gif)