• List 循环
    • code
    • code 省略键值
    • node
    • node 省略键值

    List 循环

    list 标签也是用于循环输出,解析后的本质为 foreach,同时 foreach 比较符合大家的习惯。

    code

    1. public function testCode()
    2. {
    3. $parser = $this->createParser();
    4. $source = <<<'eot'
    5. {list $list $key $value}
    6. {$key} - {$value}
    7. {/list}
    8. eot;
    9. $compiled = <<<'eot'
    10. <?php if (is_array($list)): foreach($list as $key => $value): ?>
    11. <?php echo $key; ?> - <?php echo $value; ?>
    12. <?php endforeach; endif; ?>
    13. eot;
    14. $this->assertSame($compiled, $parser->doCompile($source, null, true));
    15. }

    code 省略键值

    有时候我们不需要键值,这个时候我们在模板中写下如下的代码:

    1. public function testCodeFull()
    2. {
    3. $parser = $this->createParser();
    4. $source = <<<'eot'
    5. {list $list $value}
    6. {$value}
    7. {/list}
    8. eot;
    9. $compiled = <<<'eot'
    10. <?php if (is_array($list)): foreach($list as $value): ?>
    11. <?php echo $value; ?>
    12. <?php endforeach; endif; ?>
    13. eot;
    14. $this->assertSame($compiled, $parser->doCompile($source, null, true));
    15. }

    node

    1. public function testNode()
    2. {
    3. $parser = $this->createParser();
    4. $source = <<<'eot'
    5. <list for=list value=my_value key=my_key index=my_index>
    6. {$my_index} {$my_key} {$my_value}
    7. </list>
    8. eot;
    9. $compiled = <<<'eot'
    10. <?php $my_index = 1; ?>
    11. <?php if (is_array($list)): foreach ($list as $my_key => $my_value): ?>
    12. <?php echo $my_index; ?> <?php echo $my_key; ?> <?php echo $my_value; ?>
    13. <?php $my_index++; ?>
    14. <?php endforeach; endif; ?>
    15. eot;
    16. $this->assertSame($compiled, $parser->doCompile($source, null, true));
    17. }

    node 省略键值

    有时候我们不需要键值,这个时候我们在模板中写下如下的代码:

    1. public function testNodeFull()
    2. {
    3. $parser = $this->createParser();
    4. $source = <<<'eot'
    5. <list for=list>
    6. {$index} {$key} {$value}
    7. </list>
    8. eot;
    9. $compiled = <<<'eot'
    10. <?php $index = 1; ?>
    11. <?php if (is_array($list)): foreach ($list as $key => $value): ?>
    12. <?php echo $index; ?> <?php echo $key; ?> <?php echo $value; ?>
    13. <?php $index++; ?>
    14. <?php endforeach; endif; ?>
    15. eot;
    16. $this->assertSame($compiled, $parser->doCompile($source, null, true));
    17. }