Stepping into Smarty - Conditionals

Smarty Templates include a whole host of features and in the post I will go over some Smarty conditional statements. Conditionals are basically a way for you to selectively show certain things based on some value.

Lets say for instance that you only want to display advertising to people visiting your site that are not logged in. This way it would give people that take the extra time to register an incentive. So if we write this out it would look something like this: “If you are a guest then show ads”.

To convert this to a Smarty conditional then we could do this:

{if $smarty.session.userlevel == 5} put your ad code {/if} 

What this does is check the users session and if the userlevel is 5 (which by default is the guest user group) then show your add code.

Now that we have the basics lets get into a more complex conditional statement. For this one lets say: “If you are logged in then display a greeting. If not then display a generic welcome message”.

This would be written as:

{if $smarty.session.username<>” || $smarty.cookies.username<>“”}
Welcome {$smarty.session.username}
{else}
Welcome to our site.  Why not join?
{/if}

The first part says if they are logged in and the username is not blank then display “Welcome Name”. Next if that condition does not run then display the else. “Welcome to our site….”.

I hope this helps you better understand Smarty conditional statements.

References

Comments ↓

Leave a Reply