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

使用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条)

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装