在libs/plugins目录里新建一个function.html_options_list.php文件,内容如下:
----------------------------------------------------------------------------------------------------------
function smarty_function_html_options_list($params, &$smarty)
{
require_once $smarty->_get_plugin_filepath('shared','escape_special_chars');
$name = null;
$text = null;
$value = null;
$selected = array();
$extra = '';
foreach($params as $_key => $_val) {
switch($_key) {
case 'name':
case 'text':
case 'value':
$$_key = (string)$_val;
break;
case 'selected':
$$_key = array_map('strval', array_values((array)$_val));
break;
case 'options':
$$_key = (array)$_val;
break;
default:
if(!is_array($_val)) {
$extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_val).'"';
} else {
$smarty->trigger_error("html_options: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
}
break;
}
}
if (!isset($options) )
return ''; /* raise error here? */
$_html_result = '';
if (isset($options)) {
foreach ($options as $_i=>$_row) {
if(is_array($_row)) {
$_value = $_row[$value];
$_text = $_row[$text];
$_html_result .= '<option label="' . smarty_function_escape_special_chars($_text) . '" value="' . smarty_function_escape_special_chars($_value) . '"';
if (in_array((string)$_value, $selected)) $_html_result .= ' selected="selected"';
$_html_result .= '>' . smarty_function_escape_special_chars($_text) . '</option>' . "\n";
}
}
}
if(!empty($name)) {
$_html_result = '<select id="' . $name . '" name="' . $name . '"' . $extra . '>' . "\n" . $_html_result . '</select>' . "\n";
}
return $_html_result;
}
-----------------------------------------------------
此函数与smarty内置的html_options函数有些不一样,语法如下:
{html_options_list name='pid' options=$arealist text='name' value='eid' selected='101'}
其中options为二维数组,格式为
----------------------------------------------------------------------------------------------------------
$_DCACHE['AREA'] = array (
1 =>
array (
'eid' => '1',
'name' => '北京市',
'rid' => '0',
),
101 =>
array (
'eid' => '101',
'name' => '东城区',
'rid' => '1',
),
102 =>
array (
'eid' => '102',
'name' => '西城区',
'rid' => '1',
)
}
-----------------------------------------------------
name为表单的名称,如果不指定表单的名称的号,则直接输入<option value='2'></option>格式的信息,对于表单名称需要在模板里指定.
text为二层数组里的字段名
value为下拉项值的字段,
selected为默认选中的值
所以生成的HTML代码如下
<code><select id="pid" name="pid">
<option label="北京市" value="1">北京市</option>
<option label="上海市" value="101" selected="selected">东城区</option>
<option label="天津市" value="102">西城区</option>
</select>
</code>
目前此函数还可以进行一些改进,如让表单的名称与id不一样,允许多选和指定大小等,