Browse Source

Add ability to load template files.

Loading PHP files with templates will allow developers to easily
customize the HTML templates helpers use.
mark_story 12 years ago
parent
commit
2575b94462

+ 7 - 0
Cake/Test/TestApp/Config/test_templates.php

@@ -0,0 +1,7 @@
+<?php
+/**
+ * Template strings for testing.
+ */
+$config = [
+	'link' => '<a href="{{url}}">{{text}}</a>',
+];

+ 4 - 0
Cake/Test/TestApp/Plugin/TestPlugin/Config/test_templates.php

@@ -0,0 +1,4 @@
+<?php
+$config = [
+	'italic' => '<em>{{text}}</em>',
+];

+ 33 - 0
Cake/Test/TestCase/View/StringTemplateTest.php

@@ -2,6 +2,7 @@
 
 namespace Cake\Test\View;
 
+use Cake\Core\Plugin;
 use Cake\TestSuite\TestCase;
 use Cake\View\StringTemplate;
 
@@ -67,4 +68,36 @@ class StringTemplateTest extends TestCase {
 		$this->assertEquals('<a href="/">example</a>', $result);
 	}
 
+/**
+ * Test loading templates files in the app.
+ *
+ * @return void
+ */
+	public function testLoad() {
+		$this->assertEquals([], $this->template->get());
+		$this->assertNull($this->template->load('test_templates'));
+		$this->assertEquals('<a href="{{url}}">{{text}}</a>', $this->template->get('link'));
+	}
+
+/**
+ * Test loading templates files from a plugin
+ *
+ * @return void
+ */
+	public function testLoadPlugin() {
+		Plugin::load('TestPlugin');
+		$this->assertNull($this->template->load('TestPlugin.test_templates'));
+		$this->assertEquals('<em>{{text}}</em>', $this->template->get('italic'));
+	}
+
+/**
+ * Test that loading non-existing templates causes errors.
+ *
+ * @expectedException Cake\Error\Exception
+ * @expectedExceptionMessage Could not load configuration file
+ */
+	public function testLoadErrorNoFile() {
+		$this->template->load('no_such_file');
+	}
+
 }

+ 25 - 0
Cake/View/StringTemplate.php

@@ -1,6 +1,10 @@
 <?php
 namespace Cake\View;
 
+use Cake\Core\Plugin;
+use Cake\Configure\Engine\PhpConfig;
+use Cake\Error;
+
 /**
  * Provides a interface for registering and inserting
  * content into simple logic-less string templates.
@@ -18,6 +22,27 @@ class StringTemplate {
 	protected $_templates = [];
 
 /**
+ * Load a config file containing templates.
+ *
+ * Template files should define a `$config` variable containing
+ * all the templates to load. Loaded templates will be merged with existing
+ * templates.
+ *
+ * @param string $file The file to load
+ * @return void
+ */
+	public function load($file) {
+		list($plugin, $file) = pluginSplit($file);
+		$path = APP . 'Config/';
+		if ($plugin !== null) {
+			$path = Plugin::path($plugin) . 'Config/';
+		}
+		$loader = new PhpConfig($path);
+		$templates = $loader->read($file);
+		$this->add($templates);
+	}
+
+/**
  * Add one or more template strings.
  *
  * @param array $templates The templates to add.