Skip to content

Commit

Permalink
Add ability to load template files.
Browse files Browse the repository at this point in the history
Loading PHP files with templates will allow developers to easily
customize the HTML templates helpers use.
  • Loading branch information
markstory committed Sep 22, 2013
1 parent 168ba36 commit 2575b94
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 0 deletions.
7 changes: 7 additions & 0 deletions Cake/Test/TestApp/Config/test_templates.php
@@ -0,0 +1,7 @@
<?php
/**
* Template strings for testing.
*/
$config = [
'link' => '<a href="{{url}}">{{text}}</a>',
];
4 changes: 4 additions & 0 deletions Cake/Test/TestApp/Plugin/TestPlugin/Config/test_templates.php
@@ -0,0 +1,4 @@
<?php
$config = [
'italic' => '<em>{{text}}</em>',
];
33 changes: 33 additions & 0 deletions Cake/Test/TestCase/View/StringTemplateTest.php
Expand Up @@ -2,6 +2,7 @@

namespace Cake\Test\View;

use Cake\Core\Plugin;
use Cake\TestSuite\TestCase;
use Cake\View\StringTemplate;

Expand Down Expand Up @@ -67,4 +68,36 @@ public function testFormat() {
$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 changes: 25 additions & 0 deletions 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.
Expand All @@ -17,6 +21,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.
*
Expand Down

0 comments on commit 2575b94

Please sign in to comment.