2013-09-30 29 views
1

PHP部分在Smarty的使用html_options時

$ids = array(1, 2, 3); 
$texts = array('a', 'b', 'c'); 
$attributes = array('a1', 'b1', 'c1'); 
$smarty->assign('ids', $ids); 
$smarty->assign('texts', $texts); 
$smarty->assign('attributes', $attributes); 

TPL部分

<select name="test"> 
{html_options values=$ids output=$texts attribute=$attributes} 
</select> 

結果

<select name="test"> 
<option value="1">a</option> 
<option value="2">b</option> 
<option value="3">c</option> 
</select> 

能否添加更多定義的屬性如何增加更多的屬性?

回答

2

不幸的是,沒有這樣的功能可用。您可以直接生成選項,像這樣的代碼:

<select name="test"> 
    {foreach $ids as $id} 
    <option value="{$id}" attribute="{$attributes[[email protected]]}">{$texts[[email protected]]}</option> 
    {/foreach} 
</select> 

或者,我會建議做一些更靈活的數據結構,如:

$data = array(1 => array('attr' => 'a1', 'text' => 'a'), 
       2 => array('attr' => 'a2', 'text' => 'b'), 
       3 => array('attr' => 'a3', 'text' => 'c')); 

$smarty->assign('data', $data); 

,然後使用類似這樣的

代碼
<select name="test"> 
    {foreach $data as $item} 
    <option value="{[email protected]}" attribute="{$item.attr}">{$item.text}</option> 
    {/foreach} 
</select> 

你應該添加一些轉義值或使用auto_escape值,這只是一個基本的想法。