68 Classifieds Blog

Features

Stepping into Smarty - Conditionals

Posted on May 5, 2008 by Eric Barnes

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

April 15th, 2009 at 5:54 am

What about conditional includes … you have described a generic ‘if’ statement well, but any programming book covers that… i have found that smarty is funny about conditional includes…

i.e. {if(some var meets some criteria)} include file=”sometemplate” {else dont}

This is a key area where PHP is excellent, and was one of the initial features in php 3 to make it better than classic ASP (which was the only alterative at the time).
Due to smarty’s pre-compiled nature and no mention of this in the documentation, maybe it cannot do it.

April 15th, 2009 at 8:54 am

I have used conditional includes my self and never had any issues with it. I use something like the post outlines:
{if $var==’whatever’}
{include file=”"}
{/if}

Comments