| 148 |
lars |
1 |
assign()
|
|
|
2 |
|
|
|
3 |
assign variables/objects to the templates
|
|
|
4 |
|
|
|
5 |
Description
|
|
|
6 |
===========
|
|
|
7 |
|
|
|
8 |
void
|
|
|
9 |
|
|
|
10 |
assign
|
|
|
11 |
|
|
|
12 |
mixed
|
|
|
13 |
|
|
|
14 |
var
|
|
|
15 |
|
|
|
16 |
void
|
|
|
17 |
|
|
|
18 |
assign
|
|
|
19 |
|
|
|
20 |
string
|
|
|
21 |
|
|
|
22 |
varname
|
|
|
23 |
|
|
|
24 |
mixed
|
|
|
25 |
|
|
|
26 |
var
|
|
|
27 |
|
|
|
28 |
bool
|
|
|
29 |
|
|
|
30 |
nocache
|
|
|
31 |
|
|
|
32 |
You can explicitly pass name/value pairs, or associative arrays
|
|
|
33 |
containing the name/value pairs.
|
|
|
34 |
|
|
|
35 |
If you pass the optional third `nocache` parameter of TRUE, the variable
|
|
|
36 |
is assigned as nocache variable. See
|
|
|
37 |
[`Cacheability of Variables`](#cacheability.variables) for details.
|
|
|
38 |
|
|
|
39 |
> **Note**
|
|
|
40 |
>
|
|
|
41 |
> When you assign/register objects to templates, be sure that all
|
|
|
42 |
> properties and methods accessed from the template are for presentation
|
|
|
43 |
> purposes only. It is very easy to inject application logic through
|
|
|
44 |
> objects, and this leads to poor designs that are difficult to manage.
|
|
|
45 |
> See the Best Practices section of the Smarty website.
|
|
|
46 |
|
|
|
47 |
|
|
|
48 |
<?php
|
|
|
49 |
// passing name/value pairs
|
|
|
50 |
$smarty->assign('Name', 'Fred');
|
|
|
51 |
$smarty->assign('Address', $address);
|
|
|
52 |
|
|
|
53 |
// passing an associative array
|
|
|
54 |
$smarty->assign(array('city' => 'Lincoln', 'state' => 'Nebraska'));
|
|
|
55 |
|
|
|
56 |
// passing an array
|
|
|
57 |
$myArray = array('no' => 10, 'label' => 'Peanuts');
|
|
|
58 |
$smarty->assign('foo',$myArray);
|
|
|
59 |
|
|
|
60 |
// passing a row from a database (eg adodb)
|
|
|
61 |
$sql = 'select id, name, email from contacts where contact ='.$id;
|
|
|
62 |
$smarty->assign('contact', $db->getRow($sql));
|
|
|
63 |
?>
|
|
|
64 |
|
|
|
65 |
These are accessed in the template with
|
|
|
66 |
|
|
|
67 |
|
|
|
68 |
{* note the vars are case sensitive like php *}
|
|
|
69 |
{$Name}
|
|
|
70 |
{$Address}
|
|
|
71 |
{$city}
|
|
|
72 |
{$state}
|
|
|
73 |
|
|
|
74 |
{$foo.no}, {$foo.label}
|
|
|
75 |
{$contact.id}, {$contact.name},{$contact.email}
|
|
|
76 |
|
|
|
77 |
To access more complex array assignments see
|
|
|
78 |
[`{foreach}`](#language.function.foreach) and
|
|
|
79 |
[`{section}`](#language.function.section)
|
|
|
80 |
|
|
|
81 |
See also [`assignByRef()`](#api.assign.by.ref),
|
|
|
82 |
[`getTemplateVars()`](#api.get.template.vars),
|
|
|
83 |
[`clearAssign()`](#api.clear.assign), [`append()`](#api.append) and
|
|
|
84 |
[`{assign}`](#language.function.assign)
|