|
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 |
kenzor Smarty Rookie
Joined: 17 Feb 2004 Posts: 9
|
Posted: Thu Feb 09, 2006 2:37 am Post subject: Assign Value to Element of Array |
|
|
I needed a way to create arrays from within the template, or assign a value to an array element so I created the assignel function.
Usage: {{assignel var=myarray key=1 value='myvalue'}}
If the specified var does not exist, or is not an array a new array with only one element (the one you specify with key and value) will be created.
Code: |
function smarty_function_assignel ($_params, &$_smarty)
{
if (!isset($_params['var'])) {
$_smarty->trigger_error("assignel: missing 'var' parameter", E_USER_ERROR, __FILE__, __LINE__);
return;
}
if (!isset($_params['key'])) {
$_smarty->trigger_error("assignel: missing 'key' parameter", E_USER_ERROR, __FILE__, __LINE__);
return;
}
if (!isset($_params['value'])) {
$_smarty->trigger_error("assignel: missing 'value' parameter", E_USER_ERROR, __FILE__, __LINE__);
return;
}
if (isset($_smarty->_tpl_vars[$_params['var']]) && is_array($_smarty->_tpl_vars[$_params['var']])) {
$var = $_smarty->_tpl_vars[$_params['var']];
} else {
$var = array();
}
$var[$_params['key']] = $_params['value'];
$_smarty->assign($_params['var'], $var);
}
|
Aside: A lot of people keep saying that you should really be creating your arrays in your PHP but I am sticking to a strict MVC approach. In my case it is only because of the way I wish to display the information that an array is required, so given a different look you wouldn't need the array. Therefore the array construction must be in the template, not in PHP.
(Updated to reference $_smarty correctly when throwing errors) |
|
Back to top |
|
dodtracker Smarty n00b
Joined: 17 Jun 2007 Posts: 4
|
Posted: Mon Jun 18, 2007 4:22 am Post subject: perfect! |
|
|
Thanks! I'm using this in my application.
Template logic can require the use of arrays; for example, I'm showing the most popular item in each category from a list of categories. But, since each item can be in multiple categories and, since I want to show a different item per category, I need to save an array of already-used items.
The category-inclusion logic is something that can't (and shouldn't) be done at the template level, it's complicated and proprietary to the data.
Anyway, appreciate it!
Ben
http://www.dodtracker.com/ |
|
Back to top |
|
boots Administrator
Joined: 16 Apr 2003 Posts: 5611 Location: Toronto, Canada
|
|
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
|