Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions raelgc/view/Template.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
namespace raelgc\view {

/**
* Template Management for PHP5
* Template Management for PHP >=5
*
* The Template engine allows to keep the HTML code in some external files
* which are completely free of PHP code. This way, it's possible keep logical
Expand All @@ -15,7 +15,7 @@
* minor features.
*
* @author Rael G.C. (rael.gc@gmail.com)
* @version 2.2.7
* @version 2.3.1
*/
class Template {

Expand Down Expand Up @@ -466,7 +466,8 @@ protected function subst($value) {
* content.
*
* @param string $block the block name to be parsed
* @param boolean $append true if the content must be appended
* @param boolean $append true if the content must be appended (default)
* @return void
*/
public function block($block, $append = true) {
if(!in_array($block, $this->blocks)) throw new \InvalidArgumentException("block $block does not exist");
Expand All @@ -487,6 +488,22 @@ public function block($block, $append = true) {
if(isset($this->parents[$block])) foreach($this->parents[$block] as $child) $this->clear($child.'_value');
}

/**
* Shortcut to iterate over a block, assign values, then parse the related block.
*
* @param string $block the block name to be parsed
* @param string $varname constains a varname
* @param iterable $values any collection of values
* @param boolean $append true if the content must be appended (default)
* @return void
*/
public function mapBlock($block, $varname, $values, $append = true) {
foreach($values as $v) {
$this->$varname = $v;
$this->block($block, $append);
}
}

/**
* Returns the final content
*
Expand Down
13 changes: 12 additions & 1 deletion tests/TemplateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,6 @@ public function __toString() {
$this->assertEquals('foobar', trim($tpl->parse()));
}


public function testObjectParse()
{
$tpl = new Template(__DIR__ . '/simple_var.html');
Expand All @@ -175,6 +174,18 @@ public function setBar($bar) {
$this->assertEquals('Object', trim($tpl->parse()));
}

public function testMapBlock()
{
$tpl = new Template(__DIR__ . '/map_block.html');
$user = new class {
public $name;
};
$user->name = 'Joe';
$users = [$user];
$tpl->mapBlock('BLOCK_USERS', 'USER', $users);
$this->assertEquals('Name: Joe', trim($tpl->parse()));
}

public function testFailureSimpleObjectCaseMismatch()
{
$this->expectException(RuntimeException::class);
Expand Down
3 changes: 3 additions & 0 deletions tests/map_block.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<!-- BEGIN BLOCK_USERS -->
Name: {USER->NAME}
<!-- END BLOCK_USERS -->