Chapter 4. Smarty for Web Designers

Smarty for Web Designers > Crash Course

Now that you've seen all the technical details about PHP and Smarty configuration, it's time to show you the other side of Smarty.

Smarty's biggest advantage is its ease of use among web designers. In the following sections, we teach you how to use developed functionalities on your Smarty templates.

4.1. Crash Course

Next, we'll help you start using Smarty's main features. For a more complete reference, take a look at the Smarty documentation for web designers.[*]

[*] Information is available on the Smarty web site, "Smarty For Template Designers" (http://smarty.php.net/manual/en/smarty.for.designers.php).

Also, remember that you should first have a working Smarty environment, as explained previously.

4.1.1. Using variables

Variables are a way to store values and later perform some action on them. You can, for instance, store the name of the user and display it on a specific web page. Variables can be assigned from within PHP, loaded from configuration files, and manipulated directly in Smarty.

Let's see how you can assign variables in these three ways:


PHP assigned variables

These variables are used with a preceding dollar sign ($), like you''d do in PHP itself. They are assigned through the assign() method of the Smarty class. Variables can be scalars, associative or indexed arrays, or even object properties.


Variables created from within Smarty templates

You can also assign values to variables by using the Smarty {assign} custom function. Variables created by this method are only available within the template where the variable was created.


Variables loaded from configuration files

Configuration variables must be enclosed within hash marks (#). They can also be accessed through the $smarty.config associative array. Configuration variables are useful for centralizing most aspects of a web page, like its title, colors, and so on.

4.1.2. Variable modifiers

Once you're able to display variables on your Smarty templates, you might need to modify them for some reason. Applying a modifier is as easy as appending a pipe (|) to the variable that you want to modify. Some modifiers might have associated options that you can specify by separating them with a colon (:) right after the modifier name.

Modifiers can be applied to every kind of variable and also to custom functions, affecting their output. Keep in mind that if you apply a modifier to an array, you are applying it to every element of that array. There are a lot of different modifiers, or filters, but here we cover the most important ones:


capitalize

Capitalizes the text that's being filtered. Capitalization changes text so that every word's first letter is converted into its uppercase equivalent. This code will correctly capitalize a person's name:

       {$completeName|capitalize}


date_format

Formats a given date according to the conversion specifiers. This filter accepts the desired format as a parameter. The following Smarty code displays current time in the HH:MM format. Notice how the format is specified:

       {$smarty.now|date_format:"%H:%M"}


nl2br

Converts all newline characters into HTML <br /> tags. Useful if content arrives at your template preformatted with line breaks. This code converts an article body so that every line break prints as an HTML <br /> tag.

       {articleBody|nl2br}


wordwrap

Wraps a string to a specified width. This filter is useful when you want to fit a given text within a very limited space, like a column or a box. This can be useful if you want to display justified text, for instance. By default, text is wrapped using the newline character (\n). You can, however, specify which character to use by using a parameter just for that. The following code will display an article text-wrapped on the 50th column:

       {articleBody|wordWrap:50:"<br />"}

Modifiers can also be combined simply by concatenating them using the pipe character (|) as a separator. This code wraps text to the 30th column and then converts all line breaks into the HTML <br/> tag:

       {articleBody|wordWrap:30|nl2br}

4.1.3. Functions

The Smarty language itself exists around its functions. There are many types of functions, from control structures to content capture and variable assignment. One thing to keep in mind is that you cannot create a custom function with the same name as any of these. Here's a list of the more relevant Smarty functions:


If elseif else

These are the basic control structure statements. They work in the same way as in any other programming language:

       {if $temperature > 80}          It's hot!        {/if}

Notice how the {if} statement must be closed by an {/if}. Of course you can articulate a bit more by using {else} and {elseif}:

       {if $temperature > 80}          It's hot.        {elseif $temperature > 60}          It's warm.        {else}          It's kinda cold...        {/it}


foreach, foreachelse

These functions let you iterate over a single associative array. You must specify the array you are iterating over and the name of the variable you want to use on every iteration. The {foreachelse} function lets you specify code to be run when there are no items on the array:

       {foreach from=$citiesTemperature item=temperature}          Temperature for {$temperature.city}: {$temperature.value} degrees.        {/foreach}


include

Like the name implies, it lets you include another template in the current template. The included template inherits all variables from the current template:

       {include file="myTemplate.html"}


assign

Lets you assign a specific value to a named variable. You can assign other variables, literal values, or even a combination of both.

To assign complex math formulas, you must enclose them in backticks (`). You can then use the newly created variable like you would otherwise in your template:

       {assign var="yourVariable" value="yourValue"}


counter

Prints a count value based on its first call. After that, the counter is modified each time the function is called. You can specify the start value, the count step or interval, the count direction (up or down), and whether the value should be printed or assigned to a variable:

       {counter start="100" skip="2" direction="down"}        {counter}        {counter}


cycle

Alternates a set of predefined values. Among other things, you can specify the set of values to alternate from and whether the current value should be printed or assigned to a variable.

This function is particularly useful when you want to print a list of items with alternating background colors:

       <table>        {foreach from="$people" item="person"}          <tr bgcolor="{cycle values="white,blue"}">            <td>{$person.name}</td><td>{$person.age}</td>          </tr>        {/foreach}        </table>


mailto

Prints mailto HTML tags on the page. You can specify numerous mailing parameters and, most importantly, the encoding format you wish to use.

As you know, encoding email addresses makes it more difficult for spammers to use them. With Smarty you can choose from hexadecimal and JavaScript encodings:

       {mailto address="me@example.com" encode="hex"}

The power of Smarty doesn't end here. Besides these functions you can use all the functions and objects provided by your development team. All in-house developed functions should also be well tested and documented before web designers start using them.

4.1.4. Configuration files

Sometimes you need to reuse the same values in many different places. It would be interesting if you could store those values somewhere without having to go into PHP code all the time. Fortunately there is one such place: Smarty configuration files.

Configuration variables can be loaded into the template either by calling Smarty's {config_load} built-in function or by calling the config_load() function from within PHP.

Configuration files use the well-known INI file syntax.[dagger] This syntax has these basic elements:

[dagger] For more information, please see "INI file," on Wikipedia (http://en.wikipedia.org/wiki/INI_file).


Sections

Sections start with a declaration that must be enclosed in [ and ].


Parameters

Parameters consist of a key, or variable name, an equal sign (=) and a value, which can be enclosed in double quotes if it occupies more than one line.


Comments

A comment begins with a hash mark (#). The parser ignores all comments.


Hidden sections and variables

All sections and variables that start by a dot (.) are considered invisible. This is useful when you have variables that you don't want to expose to the template but still want to use in your PHP code.

Let's take a look at an example configuration file where we specify a section and a setting:

# The next section specifies which colors to use [colors] bodyBackgroundColor = "#efefef"

You can use the bodyBackgroundColor configuration variable by using the {config_load} function. You must specify which configuration file you want to load by using the file parameter.

You can also tell which section of the configuration file you want to load. Remember that configuration variables must be enclosed by hash marks:

{config_load file="presentation.conf" section="colors"} <html> <body bgcolor="{#bodyBackgroundColor#}"> </body> </html>

In short, configuration files can be a nice way for you to maintain certain values across your templates.

4.1.5. Debugging

Another Smarty feature that might be useful to some of you is its debugging console. Through the console you have access to a set of valuable information, such as:

  • Included templates

  • PHP assigned variables

  • Configuration variables

You can use this console simply by calling the {debug} function from within your Smarty template.

The console works by opening a pop-up window on the page you're loading. In Figure 4-1, you can see what the Smarty Debug Console looks like.

Figure 4-1. The Smarty Debug Console


It's also possible to turn on this feature for all your templates. To do so, you must set $debugging to true on the PHP script that displays your templates:

<?php $smarty->debugging = true; ?>

If you're planning to use the Debug Console, be aware that it might increase load times for your web site, and it will expose internal information to your users, so you shouldn't use it in production environment.

 

 



PHP and Smarty on Large-Scale Web Development
PHP and Smarty on Large-Scale Web Development
ISBN: 047008023X
EAN: N/A
Year: 2007
Pages: 20
BUY ON AMAZON

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net