| 148 |
lars |
1 |
Variable scopes {#language.variable.scopes}
|
|
|
2 |
===============
|
|
|
3 |
|
|
|
4 |
You have the choice to assign variables to the scope of the main Smarty
|
|
|
5 |
object, data objects created with [`createData()`](#api.create.data),
|
|
|
6 |
and template objects created with
|
|
|
7 |
[`createTemplate()`](#api.create.template). These objects can be
|
|
|
8 |
chained. A template sees all the variables of its own object and all
|
|
|
9 |
variables assigned to the objects in its chain of parent objects.
|
|
|
10 |
|
|
|
11 |
By default templates which are rendered by
|
|
|
12 |
[`$smarty->display(...)`](#api.display) or
|
|
|
13 |
[`$smarty->fetch(...)`](#api.fetch) calls are automatically linked to
|
|
|
14 |
the Smarty object variable scope.
|
|
|
15 |
|
|
|
16 |
By assigning variables to individual data or template objects you have
|
|
|
17 |
full control which variables can be seen by a template.
|
|
|
18 |
|
|
|
19 |
|
|
|
20 |
|
|
|
21 |
// assign variable to Smarty object scope
|
|
|
22 |
$smarty->assign('foo','smarty');
|
|
|
23 |
|
|
|
24 |
// assign variables to data object scope
|
|
|
25 |
$data = $smarty->createData();
|
|
|
26 |
$data->assign('foo','data');
|
|
|
27 |
$data->assign('bar','bar-data');
|
|
|
28 |
|
|
|
29 |
// assign variables to other data object scope
|
|
|
30 |
$data2 = $smarty->createData($data);
|
|
|
31 |
$data2->assign('bar','bar-data2');
|
|
|
32 |
|
|
|
33 |
// assign variable to template object scope
|
|
|
34 |
$tpl = $smarty->createTemplate('index.tpl');
|
|
|
35 |
$tpl->assign('bar','bar-template');
|
|
|
36 |
|
|
|
37 |
// assign variable to template object scope with link to Smarty object
|
|
|
38 |
$tpl2 = $smarty->createTemplate('index.tpl',$smarty);
|
|
|
39 |
$tpl2->assign('bar','bar-template2');
|
|
|
40 |
|
|
|
41 |
// This display() does see $foo='smarty' from the $smarty object
|
|
|
42 |
$smarty->display('index.tpl');
|
|
|
43 |
|
|
|
44 |
// This display() does see $foo='data' and $bar='bar-data' from the data object $data
|
|
|
45 |
$smarty->display('index.tpl',$data);
|
|
|
46 |
|
|
|
47 |
// This display() does see $foo='data' from the data object $data
|
|
|
48 |
// and $bar='bar-data2' from the data object $data2
|
|
|
49 |
$smarty->display('index.tpl',$data2);
|
|
|
50 |
|
|
|
51 |
// This display() does see $bar='bar-template' from the template object $tpl
|
|
|
52 |
$tpl->display(); // or $smarty->display($tpl);
|
|
|
53 |
|
|
|
54 |
// This display() does see $bar='bar-template2' from the template object $tpl2
|
|
|
55 |
// and $foo='smarty' form the Smarty object $foo
|
|
|
56 |
$tpl2->display(); // or $smarty->display($tpl2);
|
|
|
57 |
|
|
|
58 |
|
|
|
59 |
|
|
|
60 |
See also [`assign()`](#api.assign), [`createData()`](#api.create.data)
|
|
|
61 |
and [`createTemplate()`](#api.create.template).
|