douzhang5199 2015-01-20 20:57
浏览 164
已采纳

使用Smarty模板显示数组?

I'm trying to use Smarty to automatically insert data into a textarea.

There are two lines that will be inserted. Here's an example of what would be inserted:

John Doe
Level 1, Support Tech

Obviously each name would have a position associated with it.

I'm imagining it should be something like this:

$array-names = array("John Joe", "Jane Doe", "Random Name");
$array-positions = array("Level 1, Support Tech", "Level 2, Sales Staff", "Level 2, Billing Team");

And then I would just need to randomly pick one to automatically insert - but they need to match. For example, John Doe should always have Level 1, Support Tech listed below.

Is doing something like this possible in Smarty or am I on the totally wrong track...?

  • 写回答

2条回答 默认 最新

  • doumingo04696 2015-01-20 21:36
    关注

    Couldn't you create an array in Smarty in the order you described

    Then use this following method in smarty to display the array, for example:

    <?php
    //an organized array with names and positions that match
    $array_names_positions = array(1 => array('Name' => 'John Doe', 'position' => 'Level 1, Support Tech'),
                                  2 => array('Name' => 'Jane Doe', 'position' => 'Level 2, Sales Staff')
                                  3 => array('Name' => 'Random Name', 'position' => 'Level 2, Billing Team')
                        );
    
    //assign the array to $items var
    $smarty->assign('items', $array_names_positions);
    
    //draw a textarea and display the array, (you can work on your display mechanism to limit or to display all here
    <textarea>
    {foreach from=$items key=myId item=i}
      {$i.name}: {$i.position}
    {/foreach}
    </textarea>
    

    When you say randomly pick one to automatically insert, you can either randomly display one in the textarea and have a submit button to save that record to db.

    And if you want to randomize you can use $array_names_positions[mt_rand(0,count($array_names_positions)-1)] to shuffle

    You can put the php code in the .tpl file; becareful when you insert php code in a smarty template file. Be sure to use:

    {php}
    //php code here
    {/php} 
    

    in your smarty template. Don't mix too much php code with the template file; it defeats the purpose of the template to keep it balanced. If the php code has ton of logic you should put that in a smarty controller.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?