Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get COOKIE in Smarty

When User already login, i want to show some link in page

<{if(!empty($_COOKIE['USER']))}>
   <a href="domain.com/page-a.html">TEXT A</a>
<{else}> <a href="domain.com/page-b.html">TEXT B</a>
<{/if}>    

but does not work


Found the answer myself, just replace :

<{if(!empty($_COOKIE['USER']))}>

with

<{if $smarty.cookies.USER!=''}>

Yihaaa !!!

like image 818
prieku Avatar asked Jul 26 '14 08:07

prieku


1 Answers

For me it's rather not good practice to do it that way.

You should do it in PHP:

if (!empty($_COOKIE['USER'])) {
   $smarty->assign('page','a');
}
else {
   $smarty->assign('page','b');
}

And then in Smarty:

{if $page eq 'a'}
<a href="domain.com/page-a.html">TEXT A</a>
{else}
<a href="domain.com/page-b.html">TEXT B</a>
{/if}

What's the benefit of such attitude? In template you don't care how $page is calculated. It may be calculated by session or by any other reason and template just don't care because it's only care about $page value. If you decide to change implementation you will need only change it in PHP and not in both PHP and Smarty.

You could also consider using $_SESSION instead of $_COOKIE - what if user changes/set his cookie value? He will get access to page b even if he shouldn't have such access.

like image 160
Marcin Nabiałek Avatar answered Sep 29 '22 00:09

Marcin Nabiałek