Introduction to Smarty Variables

In general, variables are containers that store a chunk of data. Smarty variables are no different but in most cases they are populated using a PHP script. While naming the variables, follow the same convention as you did in PHP. For example, here are some rules:

  • Don’t start with a numerical character
  • Avoid using the name of any reserved variable of PHP (like $_POST or $_SERVER)
  • Give it a meaningful name (for the sake of simplicity)
  • Start it with a $ sign

Moreover all Smarty variables must be enclosed with braces {}. These are the basic conventions for naming Smarty variables. Let’s see a small template and an example of assigning variables in a script.

sample.tpl

<html>
<body>
Hello {$name}, {$greetings}. 
</body>
</html>

Save this file in your templates folder as sample.tpl. In this template, there are two variables named {$name} and {$greetings}. We will now populate these variables using our PHP script.

sample.php

<?php
include(“libs/smarty.class.php”);
$smarty = new smarty();
$sample_name = “Jamil Ahmed”;
$smarty->assign(“name”, $sample_name);
$smarty->assign(“greetings”, “Good Morning”);
$smarty->display(“sample.tpl”);
?>

Save this file as sample.php and run it. You will get the following result:

Introduction to Smarty Variables

As you can see, Smarty substitutes the template variable {$name} and {$greetings} with data supplied from your PHP script. You can assign variables with the assign() method. In the assign() method, the first parameter is the name of the Smarty variable and the second parameter is the data you want to assign to it. To assign a variable in the template itself, use the assign() function inside your template like this:

{assign var = “date” value = “27th September,  2005”}
Today is {$date}

This will output Today is 27th September, 2005. You don’t need to assign any extra data to this {$date} variable. You can assign any data, array and user-defined objects (mainly classes) in a Smarty variable. If you pass an object to your template, you can even access its methods and properties inside your template. Smarty gives you ultimate flexibility while templating. Later in this chapter we will discuss arrays.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.63.87