|
Smarty
WARNING: All discussion is moving to https://reddit.com/r/smarty, please go there! This forum will be closing soon. |
|
View previous topic :: View next topic |
Author |
Message |
lorenzo.s Smarty n00b
Joined: 11 Oct 2009 Posts: 2
|
Posted: Sun Oct 11, 2009 11:14 am Post subject: Assign objects to template |
|
|
Hi everyone.
Often I assign objects to template like: Code: | $user = new User(12); // Loads the user data
$smarty->assign('user', $user); |
I don't use assign_by_ref() because I need copies of the object (for
example, in a loop I can overwrite $user variable with another user).
The problem is that in the template I have to use {$user->property}
instead of {$user.property}. The dot will be better beacase in the
HTML template I don't have to know if $user is an object or an
associative array, I can load it as I want.
So I have made this modify in the Smarty.class.php in the assign() method: Code: | function assign($tpl_var, $value = null)
{
if (is_array($tpl_var)){
foreach ($tpl_var as $key => $val) {
if ($key != '') {
$this->_tpl_vars[$key] = (is_object($val) ? get_object_vars($val) : $val);
}
}
} else {
if ($tpl_var != '')
$this->_tpl_vars[$tpl_var] = (is_object($value) ? get_object_vars($value) : $value);
}
} |
If $value is an object, i simply use get_object_vars($value), and all
seems to work.
What do you think about it?
Thank you,
Lorenzo. |
|
Back to top |
|
mohrt Administrator
Joined: 16 Apr 2003 Posts: 7368 Location: Lincoln Nebraska, USA
|
Posted: Sun Oct 11, 2009 1:47 pm Post subject: |
|
|
thats fine, until someone wants to assign the object so they can call methods or use the -> syntax.
Why not just assign your properties as an array if you want them that way?
Code: | $smarty->assign('user',get_object_vars($user)); |
|
|
Back to top |
|
lorenzo.s Smarty n00b
Joined: 11 Oct 2009 Posts: 2
|
Posted: Sun Oct 11, 2009 5:24 pm Post subject: |
|
|
mohrt wrote: | Why not just assign your properties as an array if you want them that way?
Code: | $smarty->assign('user',get_object_vars($user)); |
|
Practicalness
And because I can also do something like:
Code: | $smarty->assign('users', User::getAll()); |
For example |
|
Back to top |
|
douglassdavis Smarty Junkie
Joined: 21 Jan 2008 Posts: 541
|
Posted: Sun Oct 11, 2009 5:52 pm Post subject: |
|
|
becomes pretty impractical when you actually need the object.
In general I don't like to make changes to the Smarty class that restrict my options in the future, but that's just one mans opinion. |
|
Back to top |
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|