Browse Source

Add push/pop onto StringTemplate

These methods will make managing templates simpler in FormHelper which
needs to manage templates temporarily.
mark_story 11 years ago
parent
commit
e85e241278
2 changed files with 52 additions and 2 deletions
  1. 33 2
      src/View/StringTemplate.php
  2. 19 0
      tests/TestCase/View/StringTemplateTest.php

+ 33 - 2
src/View/StringTemplate.php

@@ -52,6 +52,13 @@ class StringTemplate {
 	];
 	];
 
 
 /**
 /**
+ * A stack of template sets that have been stashed temporarily.
+ *
+ * @var
+ */
+	protected $_configStack = [];
+
+/**
  * Contains the list of compiled templates
  * Contains the list of compiled templates
  *
  *
  * @var array
  * @var array
@@ -68,14 +75,38 @@ class StringTemplate {
 	}
 	}
 
 
 /**
 /**
+ * Push the current templates onto the template stack.
+ *
+ * @return void
+ */
+	public function push() {
+		$this->_configStack[] = $this->_config;
+	}
+
+/**
+ * Restore the most recently pushed set of templates.
+ *
+ * Restoring templates will invalidate all compiled templates.
+ *
+ * @return void
+ */
+	public function pop() {
+		if (empty($this->_configStack)) {
+			return;
+		}
+		$this->_config = array_pop($this->_configStack);
+		$this->_compiled = [];
+	}
+
+/**
  * Registers a list of templates by name
  * Registers a list of templates by name
  *
  *
  * ### Example:
  * ### Example:
  *
  *
  * {{{
  * {{{
  * $templater->add([
  * $templater->add([
- *	'link' => '<a href="{{url}}">{{title}}</a>'
- *	'button' => '<button>{{text}}</button>'
+ *   'link' => '<a href="{{url}}">{{title}}</a>'
+ *   'button' => '<button>{{text}}</button>'
  * ]);
  * ]);
  * }}}
  * }}}
  *
  *

+ 19 - 0
tests/TestCase/View/StringTemplateTest.php

@@ -209,4 +209,23 @@ class StringTemplateTest extends TestCase {
 		$this->assertEquals([null, null], $this->template->compile('link'));
 		$this->assertEquals([null, null], $this->template->compile('link'));
 	}
 	}
 
 
+/**
+ * test push/pop templates.
+ *
+ * @return void
+ */
+	public function testPushPopTemplates() {
+		$this->template->add(['name' => '{{name}} is my name']);
+		$this->assertNull($this->template->push());
+
+		$this->template->add(['name' => 'my name']);
+		$this->assertEquals('my name', $this->template->get('name'));
+
+		$this->assertNull($this->template->pop());
+		$this->assertEquals('{{name}} is my name', $this->template->get('name'));
+
+		$this->assertNull($this->template->pop());
+		$this->assertNull($this->template->pop());
+	}
+
 }
 }