How to get COOKIE in Smarty
Asked Answered
S

3

8

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

Symons answered 26/7, 2014 at 8:50 Comment(0)
N
1

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.

Nial answered 26/7, 2014 at 10:42 Comment(2)
Nothing wrong with using cookies in the template... especially considering, as OP mentioned, you can use $smarty.cookies to access them.Quigley
Answer is not a solution to the problem, it is a recommendation to not to have problem in general. Sometimes you may need to read cookies in template files, for instance in development to quickly check cookie and dump if debug modeMagel
I
1

This is what you need.

{$smarty.cookies.$thecookiename} {if $smarty.cookies.foo == bar} Hello world {else} Haha {/if}

Implantation answered 3/4, 2023 at 14:24 Comment(0)
K
0

Get the Cookies in Smarty using the below syntax

{$smarty.cookies.$cookiename}. $cookiename is the name of the cookie variable.

K answered 15/5, 2023 at 12:0 Comment(1)
this answer has already been mentioned, make sure not to repost people's answers.Implantation

© 2022 - 2024 — McMap. All rights reserved.