Skip to content
Permalink
Browse files

Add ability to load template files.

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 2575b944623d267687767e7eb01162cf27bfc486
@@ -0,0 +1,7 @@
<?php
/**
* Template strings for testing.
*/
$config = [
'link' => '<a href="{{url}}">{{text}}</a>',
];
@@ -0,0 +1,4 @@
<?php
$config = [
'italic' => '<em>{{text}}</em>',
];
@@ -2,6 +2,7 @@
namespace Cake\Test\View;
use Cake\Core\Plugin;
use Cake\TestSuite\TestCase;
use Cake\View\StringTemplate;
@@ -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');
}
}
@@ -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.
@@ -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.
*

0 comments on commit 2575b94

Please sign in to comment.
You can’t perform that action at this time.