File modules/util/test/MustacheTest.class.php

Last commit: Fri Feb 26 19:58:56 2021 +0100	Jan Dankert	More tests for the Mustache template parser.
1 <?php 2 3 namespace util\test; 4 5 use util\Mustache; 6 7 class MustacheTest extends TestCase { 8 9 10 public function testTemplate() { 11 12 $source = <<<SRC 13 Hello {{planet}}, {{& planet }}.{{! Simple example with a simple property }} 14 15 {{#test}} 16 Yes, this is a {{test}}. {{! yes, it is}} 17 {{/test}} 18 {{^test}} 19 No, this is not a {{test}}. {{ ! will not be displayed, because test is not false }} 20 {{/test}} 21 22 {{#car}} 23 My Car is {{color}}. {{! this is a property of the array car }} 24 It drives on {{& planet }}.{{! this property is inherited from the upper context }} 25 {{/}} 26 27 {{#house}} 28 My House is {{size}}. {{! this property is read from an object }} 29 {{/}} {{! short closing tags are allowed }} 30 31 Some names: 32 {{#names}} 33 my name is {{ name }}.{{! yes, spaces are allowed}} 34 {{/names}} 35 36 {{#empty}} 37 this is not displayed {{! because the list is empty }} 38 {{/empty}} 39 40 {{#upper}} 41 Hello again, {{planet}}. {{!displayed in uppercase}} 42 {{/}} 43 44 <h1>Partials</h1> 45 {{> mycoolpartial}} 46 47 <h1>Changing Delimiters</h1> 48 Default: {{name}} 49 {{=$( )=}} 50 Bash-Style: $(name) 51 Default should not work here: {{name}} 52 53 $(={{ }}=) 54 Default again: {{name}} 55 56 <h1>Dot notation</h1> 57 this will not work: {{building}} 58 but this is the color of the roof: {{building.roof.color}} 59 60 61 SRC; 62 63 $m = new Mustache(); 64 $m->partialLoader = function($name) { 65 return "\nThis is a partial named ".$name.". It may include variables, like the name '{{name}}'.\n\n"; 66 }; 67 $m->parse( $source ); 68 69 //echo 'Object: <pre><code>'; print_r($m); echo '</code></pre>'; 70 71 $data = array( 72 'planet' => '<b>world</b>', 73 'test' => 'Test', 74 'name' => 'Mallory', 75 'car' => array('color'=>'red'), 76 'house' => (object) array('size'=>'big' ), 77 'names' => array( 78 array('name'=>'Alice'), 79 array('name'=>'Bob') 80 ), 81 'empty' => array(), 82 'upper' => static function($text) { return strtoupper($text); }, 83 'building' => array('roof'=>array('color'=>'gray')) 84 85 ); 86 87 $this->assertNotEmpty( $m->render( $data ) ); 88 } 89 90 public function testEmptyTemplate() { 91 $m = new Mustache(); 92 $m->parse( '' ); 93 94 95 $this->assertEmpty( $m->render( [] ) ); 96 97 } 98 99 100 101 public function testOnlyOneVariable() { 102 $m = new Mustache(); 103 $m->parse( '{{name}}' ); 104 105 106 $this->assertEquals('Pete', $m->render( ['name'=>'Pete'] ) ); 107 } 108 109 110 111 }
Download modules/util/test/MustacheTest.class.php
History Fri, 26 Feb 2021 19:58:56 +0100 Jan Dankert More tests for the Mustache template parser. Thu, 10 Sep 2020 23:46:04 +0200 Jan Dankert New: Simple Unit-Testing.