Smarty Tips: Things you can do with Templates

Forum
Last Post
Threads / Messages

Kyttias

Super Moderator
Super Mod
Joined
Jan 26, 2014
Messages
849
Points
18
Mysidian Dollar
58,199
Mysidia is built with the Smarty template system. Here's some fun facts:

You can write multiple conditions using the {if} {elseif} {elseif} {else} {/if} style. In Smarty, you can also implement a nested {if} {/if} block.

You can display the current date in your template with {$smarty.now|date_format} and it will print in the format Jul 15, 2014. For the time, check out {$smarty.now|date_format:"%H:%M"} for military time that prints 16:45, or {$smarty.now|date_format:"%I:%M %p"} for 04:45 PM. If you know how php prints dates, you can probably figure out how to customize this a ton!

For fun, pop open classes/class_template.php and inside private function assignTemplateVars(){ after it's row of this->s are done, add these:

PHP:
$mysidia = Registry::get("mysidia");
$this->assign("logged_in",$mysidia->user->isloggedin);
$this->assign("username",$mysidia->user->username); 
$this->assign("cash",$mysidia->user->getcash());
$messages = $mysidia->db->select("messages", array(), "touser='{$mysidia->user->username}' and status='unread'")->rowCount(); 
$this->assign("messages",$messages);

This has assigned four variables to Smarty.

In your template.tpl, you can now do this:

Code:
{if $logged_in} 
<a href="{$home}profile/view/{$mysidia->user->username}">{$username}</a>		
${$cash} {$mysidia->settings->cost}
<a href="{$home}messages">{$messages} Messages</a>
<a href="{$home}login/logout">Log Out</a>
{else}
Please <a href="{$home}login/logout">Log In</a> or <a href="{$home}register">Sign Up</a>!
{/if}

The above will:
- only display if a user is logged in
- print their username, which will link to their profile
- show how much currency they have and the name of your currency
- show how many messages they have, and a link to go check them out
- show a log out link when they are logged in
- when they aren't logged in, it will ask them to log in or sign up

You'll definitely want to work around this and make it pretty. ^_~

Another example might be a message that shows up 30% of the time:
Code:
{if rand(0,100) <= 30} Winner! {/if}
 
Last edited:
+Bump plus more examples of possibilities:

(If using the $cash variable set in the above post!)
Code:
{if $cash < 7777}User has more than 7777 currency!{/if}
{if $cash > 7777}User has less than 7777 currency!{/if}

Adding in a user's online variable to classes/class_template.php:
PHP:
$online = $mysidia->db->select("online", array(), "username != 'Visitor'")->rowCount();
$this->assign("online","{$online} Users Online");

To be used like (this will link to a page that shows who is online):
Code:
<a href="{$home}online">{$online}</a>

Another possible use:
Code:
{if $online > 50}More than 50 users online!{/if}
{if $online < 10}Less than 10 users online!{/if}

You could also use these (in addition to the two variables above to check for users online) in classes/class_template.php:
PHP:
$guests = $mysidia->db->select("online", array(), "username = 'Visitor'")->rowCount();
$this->assign("population","{$online} Users Online + {$guests} Guests");

Then you would use {$population} to print out something like "10 Users Online + 5 Guests". Perhaps it'd look nice in a footer, if that fits your site? This could also be used in an 'if' statement if you wanted something to happen if you had a certain number of guests online at once! Get creative. ^^

And back into classes/class_template.php, you can set up messages to display at specific times of the day (server time - good for promo codes people can't cheat and use their computer's clock to get):

PHP:
$now = new DateTime();		
$hrs = $now->format('G');
if ($hrs >  0) $msg = "<b>After Hours Promo Code:</b> PC0000"; // After midnight
if ($hrs >  5) $msg = "<b>Dawn Promo Code:</b> PC0005"; // After 5am
if ($hrs >  7) $msg = "<b>Morning Promo Code:</b> PC0507"; // After 7am
if ($hrs > 12) $msg = "<b>Afternoon Promo Code:</b> PC0712"; // After noon
if ($hrs > 17) $msg = "<b>Evening Promo Code:</b> PC1217"; // After 5pm
if ($hrs > 22) $msg = "<b>Dusk Promo Code:</b> PC1722"; // After 10pm
$this->assign("timemsg",$msg);

These would be displayed with {$timemsg}.

Keep it mind that you can infinitely combine if statements with Smarty in your template. So imagine something with a 20% chance of happening only if it is between noon and five and there are less than x amount of people online.
 
Ah, here's another one, this will display a user's avatar using {$avatar} in the template:

PHP:
       $profile = $mysidia->db->select("users_profile", array("uid", "avatar"), "username = '{$mysidia->user->username}'")->fetchObject();
        $img = "<img src='../../".$profile->avatar."' class='avatar'>";
        $this->assign("avatar",$img);

I have it creating an image with a class of 'avatar' which you can set into your css stylesheet to have set dimensions of your choosing. ^^
 
Since I was asked to explain all this in more detail while helping someone, here's a more detailed explanation of how all this works.

Ok, so, as I said, let's open up classes/class_template.php. Find where private function assignTemplateVars(){ is. You'll see this inside of it:

PHP:
$this->assign("version", Mysidia::version);
$this->assign("root", $this->scriptRoot);
$this->assign("home", $this->tempRoot);
$this->assign("temp", $this->temp);
$this->assign("css", $this->css);
$this->assign("js", $this->js);

Cool. Leave those there. These are defining variables that help you in the template file to link places easily. (Take a peek in your header.tpl, you'll see a couple of them being used -- {$home}{$temp} -- see?)

Alright, beneath this small tower of $this->assign();s, we're going to assign some variables of our own. In this example, the user's current currency and the name of your site's currency.

First, we will need the line $mysidia = Registry::get("mysidia");. We need this so we can have the variable '$mysidia' contain a dynamic, yet static, link to the parent class called "mysidia", so we can invoke methods and properties from it. Bellow you'll see that 'user' and 'settings' are child classes of '$mysidia' and the functions and variables that come after them are literally found inside classes/class_user.php and classes/class_settings.php. You only need to define $mysidia once inside of a function, so best to do it very early on.

The next line we'll need is $this->assign("cash",$mysidia->user->getcash());. We're calling the template class, '$this' since its the one we're currently in, to use the function 'assign()' to assign a Smarty variable to the word "cash", and the variable we're assigning is the result of the 'getcash()' function found inside the 'user' class, a child class of the '$mysidia' class.

And finally, this is optional -- if you want the name of your currency as defined in your settings (hint: inside the 'settings' class this variable is known as 'cost' and is being pulled from the database table adopts_settings) you can obtain it using the line $this->assign("currency",$mysidia->settings->cost);, which will assign the variable 'cost' inside the 'settings' class, a child class $mysidia, to the word "currency".

So, here we go:
PHP:
$mysidia = Registry::get("mysidia");
$this->assign("cash",$mysidia->user->getcash());
$this->assign("currency",$mysidia->settings->cost);

Ok, our variables are now ready to use. But what happens if the user is not logged in? Good question. The {$cash} variable will remain empty, but the {$currency} variable still holds the name of the site's currency. If you want this information to only display while the user is logged in, you'll also want this line:

PHP:
$this->assign("logged_in",$mysidia->user->isloggedin);

{$logged_in} is now also a variable, and I'll show you how to use it in a sec.

Now that these are in place, save the template class file and be sure to reupload it to your server. You can now head over to your template file, template.tpl -- the one I had you create for your theme in the original post. We assigned data to the variables {$cash} and {$currency}. Place these wherever you like, save, upload the updated file, and go view your site!

Great. Now to only make them display if the user is logged in. Smarty can handle some basic if-statements inside curly braces, like this:

PHP:
{if $logged_in}
        {$cash} {$currency}
{else}
        You are not logged in! <a href="{$home}register">Make an account?</a>
{/if}
 
Hello! I have been doing some playing with the 1.3.6 script and I was struggling to get these working with it, but after some messing about I got it lol. So here is how I did it, in case anyone wants to use them.

Also I'm not the best so if anyone way more knowledgeable than me wants to tell me I've done it wrong or a better/easier way of doing it totally go for it :ROFLMAO::ROFLMAO:

The assignTemplateVars() has been moved from where it was before now that 1.3.6 has gotten rid of the class_ files. It is now in resource/core/template.php. So find and open that.

To get the values working I had to add at the top:

PHP:
use Resource\Model\DomainModel;

I put it at the bottom of the other 'use Resource' lines.

Now scroll down until you find assignTemplateVars() and under the last line put this (make sure it's before the curly bracket):

PHP:
$mysidia = Registry::get("mysidia");
 $this->assign("logged_in",$mysidia->user->isLoggedIn());
$this->assign("username",$mysidia->user->getUsername());
$this->assign("cash",$mysidia->user->getMoney());
$this->assign("currency",$mysidia->settings->cost);
$this->assign("message_num", $mysidia->user->countMessages());
$online = $mysidia->db->select("online", array(), "username != 'Guest'")->rowCount();
$this->assign("online","{$online}");
$guests = $mysidia->db->select("online", array(), "username = 'Guest'")->rowCount();
$this->assign("guests","{$guests}");

Now open model/domainmodel/visitor.php. We need to add getMoney and countMessages into it or the site gives an error.

Put this somewhere, I put it underneath the isLoggedIn part:

PHP:
public function getMoney(){
return FALSE;
}

public function countMessages(){
return FALSE;
}

Now we can open our themes template.tpl and put this somewhere:

HTML:
<!-- If the user is logged in... -->
{if $logged_in}
Hi, <a href="{$home}profile/view/{$username}">{$username}</a><br><br> <!-- Show username -->
You have {$cash} {$currency}<br><br> <!-- Display amount of money and currency name -->
                       
<!-- Display amount of messages you have IF you have any,
     if you don't just display a link to messages-->
<a href="{$home}messages">Messages {if {$message_num} >= 1}({$message_num}){/if}</a>
<br><br>

<a href="{$home}login/logout">Log Out</a>
{else}
                   
<!-- If the user is logged out... -->
Please <a href="{$home}login">Log In</a> or <a href="{$home}register">Sign Up</a>!
{/if}
<br><br>

<!-- Display online users and guests, is there is only 1 user online display 'User'. If there are 0
       or more than 1 online display 'Users'. If there are 0 guests, don't display the guest text,
       if there is 1, display 'Guest', if 2 or more display 'Guests'. -->
<a href="{$home}online">{$online} {if {$online == 1}}User{else}Users{/if} Online {if {$guests} >= 1}+ {$guests} Guest{if {$guests} >= 2}s{/if}!{/if}</a>

Hope that helps someone! If you try it and something doesn't work let me know and I can attempt to troubleshoot for you. :)

Here is what it should look like, I am playing with the CSS so it looks a bit broken, just ignore that lol

Logged in:

2021-12-26 13_30_17-Bean Pets and 21 more pages - Personal - Microsoft Edge.png

Logged Out:

2021-12-26 13_30_34-Bean Pets and 21 more pages - Personal - Microsoft Edge.png
 
Last edited:
Adding on to my stuff above, the messages part will count how many messages a user has, but NOT if they're unread. So it will print a number even if they have read them. So if you want to display a count of unread messages...

Put this in template.php:

PHP:
$messages = $mysidia->db->select("messages", [], "touser = '{$mysidia->user->getID()}' and status='unread'")->rowCount();
$this->assign("messages",$messages);

And then use {$messages} to display unread messages.

You can use this with the {$messages_num} from before if you'd like to display total messages as well as unread ones...
 
Last edited:
Managed to get avatars working with the help of Nemesis on the Discord (thank you!)

In template.php put this:

PHP:
$profile = $mysidia->db->select("users_profile", array("uid", "avatar"), "uid = '{$mysidia->user->getID()}'")->fetchObject();
if ($profile == NULL) $img = "";
else $img = "<img src='../../".$profile->avatar."' class='avatar'>";
$this->assign->("avatar",$img);

That assigns the avatar image if the user has a profile and if they don't (ie are a visitor) it assigns nothing. :giggle:

To use it use {$avatar}.
 
Last edited:
Got a few more smarty things for 1.3.6!

First of all showing your favourite pet. Now this is probably a really long-winded way of doing this, would NOT be surprised if there is a better way, but hey... it works... :ROFLMAO: It's been tested with logged out users, as well as logged in users that both have a favpet assigned as well as don't have one assigned.

PHP:
/* Get a user's favourite pet */
        $favpetID = $mysidia->db->select("users_profile", array("uid", "favpet"), "uid = '{$mysidia->user->getID()}'")->fetchObject();
        if ($favpetID == NULL) $favpetInfo = "";
        else $favpetInfo = $mysidia->db->select("owned_adoptables", array("aid", "adopt", "name", "currentlevel"), "aid = '{$favpetID->favpet}'")->fetchObject();
        if ($favpetInfo == NULL) $favpetImg = "";
        elseif ($favpetInfo != '0') $favpetImg = $mysidia->db->select("levels", array("lvid", "adopt", "level", "primaryimage"), "adopt = '{$favpetInfo->adopt}' and level = '{$favpetInfo->currentlevel}'")->fetchObject();
        if ($favpetID == NULL || $favpetInfo == '0') $petImg = "";
        elseif ($favpetInfo != NULL || $favpetInfo != '0') $petImg = "<a href='../../myadopts/manage/".$favpetID->favpet."'><img src='".$favpetImg->primaryimage."' title='Your favourite pet'></a>";
        else $petImg = "Something has gone wrong with this data... please contact a site admin for assistance.
                        <br><br>Please include information such as what you were doing when you saw this message, as
                        well as screenshots, if possible!";
        $this->assign("favpet",$petImg);

Use {$favpet} to call it.

  Spoiler: Optional alternative if you have Bootstrap 5 installed 

PHP:
/* Get a user's favourite pet */
        $favpetID = $mysidia->db->select("users_profile", array("uid", "favpet"), "uid = '{$mysidia->user->getID()}'")->fetchObject();
        if ($favpetID == NULL) $favpetInfo = "";
        else $favpetInfo = $mysidia->db->select("owned_adoptables", array("aid", "adopt", "name", "currentlevel"), "aid = '{$favpetID->favpet}'")->fetchObject();
        if ($favpetInfo == NULL) $favpetImg = "";
        elseif ($favpetInfo != '0') $favpetImg = $mysidia->db->select("levels", array("lvid", "adopt", "level", "primaryimage"), "adopt = '{$favpetInfo->adopt}' and level = '{$favpetInfo->currentlevel}'")->fetchObject();
        if ($favpetID == NULL || $favpetInfo == '0') $petImg = "";
        elseif ($favpetInfo != NULL || $favpetInfo != '0') $petImg = "<figure><a href='../../myadopts/manage/".$favpetID->favpet."'><img src='".$favpetImg->primaryimage."' class='favpet img-fluid border border-3 rounded mx-auto d-block' title='Your favourite pet'></a><figcaption class='pt-2 favpetcap' style='font-size: 1.25rem;'><strong>{$favpetInfo->name}</strong></figcaption></figure>";
        else $petImg = "Something has gone wrong with this data... please contact a site admin for assistance.
                        <br><br>Please include information such as what you were doing when you saw this message, as
                        well as screenshots, if possible!";
        $this->assign("favpet",$petImg);

This will display using Bootstrap classes and look like this:

2022-01-04 07_28_08-Bean Pets and 14 more pages - Personal - Microsoft​ Edge.png

You can also click the image to go manage them!


  Spoiler: Optional if you have Kyttias' tooltips installed (from shop mod, inventory mod, etc) 

Add the below to the adoptables image OR the above <figure> to add a tooltip to the fav pet.

CSS:
rel='tooltip' title='Your favourite pet, {$favpetInfo->name}!<br><em>Click to manage</em>'

Example with Bootstrap:

PHP:
<figure rel='tooltip' title='Your favourite pet, {$favpetInfo->name}!<br><em>Click to manage</em>'><a href='../../myadopts/manage/".$favpetID->favpet."'><img src='".$favpetImg->primaryimage."' class='favpet img-fluid border border-3 rounded mx-auto d-block' title='Your favourite pet'></a><figcaption class='pt-2 favpetcap' style='font-size: 1.25rem;'><strong>{$favpetInfo->name}</strong></figcaption></figure>

Example WITHOUT Bootstrap:

PHP:
<a href='../../myadopts/manage/".$favpetID->favpet."'><img src='".$favpetImg->primaryimage."' rel='tooltip' title='Your favourite pet, {$favpetInfo->name}!<br><em>Click to manage</em>'></a>

This is what it looks like (I use Bootstrap and have tweaked the tooltip CSS a bit):

2022-01-04 07_32_59-Bean Pets and 14 more pages - Personal - Microsoft​ Edge.png


Next this is just a little fun thing that you can add if you want to make a random greeting for your users. It uses greetings in a random array and displays them!


PHP:
/* Greetings array to display different greetings randomly */
        $sentences = array('Hello,', 'Hi,', 'Welcome,', 'Greetings,', 'Howdy,', 'Good day,', 'Hey,');
        shuffle($sentences);
        $this->assign('sentence', $sentences[0]);

Then use {$sentence} to display the greeting! They include commas so make sure to add the username using {$username} in your template.tpl if you have assigned that one.

It should display something like this:

2022-01-04 07_22_17-Bean Pets and 14 more pages - Personal - Microsoft​ Edge.png 2022-01-04 07_22_27-Bean Pets and 14 more pages - Personal - Microsoft​ Edge.png

They randomise on refresh!

This is the code that displays it like mine:

HTML:
<em>{$sentence} <a href='{$home}profile/view/{$username}'>{$username}</a></em>

Their username links to their profile. :D

That's it for today lol.
 
Managed to get avatars working with the help of Nemesis on the Discord (thank you!)

In template.php put this:

PHP:
$profile = $mysidia->db->select("users_profile", array("uid", "avatar"), "uid = '{$mysidia->user->getID()}'")->fetchObject();
if ($profile == NULL) $img = "";
else $img = "<img src='../../".$profile->avatar."' class='avatar'>";
$this->assign->("avatar",$img);

That assigns the avatar image if the user has a profile and if they don't (ie are a visitor) it assigns nothing. :giggle:

To use it use {$avatar}.
for some reason when I try to add this to template.php the site breaks >-< I'm adding it as is so I'm confused on what I'm doing wrong
edit: figured it out lol
the second -> in
PHP:
$this->assign->("avatar",$img);
was causing an error
 
Last edited:

Similar threads

Users who are viewing this thread

  • Forum Contains New Posts
  • Forum Contains No New Posts

Forum statistics

Threads
4,267
Messages
33,048
Members
1,602
Latest member
BerrieMilk
BETA

Latest Threads

Latest Posts

Top