3 * This file is part of the Text_Template package.
5 * (c) Sebastian Bergmann <sebastian@phpunit.de>
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
12 * A simple template engine.
14 * @since Class available since Release 1.0.0
21 protected $template = '';
26 protected $openDelimiter = '{';
31 protected $closeDelimiter = '}';
36 protected $values = array();
42 * @throws InvalidArgumentException
44 public function __construct($file = '', $openDelimiter = '{', $closeDelimiter = '}')
46 $this->setFile($file);
47 $this->openDelimiter = $openDelimiter;
48 $this->closeDelimiter = $closeDelimiter;
52 * Sets the template file.
55 * @throws InvalidArgumentException
57 public function setFile($file)
59 $distFile = $file . '.dist';
61 if (file_exists($file)) {
62 $this->template = file_get_contents($file);
65 else if (file_exists($distFile)) {
66 $this->template = file_get_contents($distFile);
70 throw new InvalidArgumentException(
71 'Template file could not be loaded.'
77 * Sets one or more template variables.
79 * @param array $values
82 public function setVar(array $values, $merge = TRUE)
84 if (!$merge || empty($this->values)) {
85 $this->values = $values;
87 $this->values = array_merge($this->values, $values);
92 * Renders the template and returns the result.
96 public function render()
100 foreach ($this->values as $key => $value) {
101 $keys[] = $this->openDelimiter . $key . $this->closeDelimiter;
104 return str_replace($keys, $this->values, $this->template);
108 * Renders the template and writes the result to a file.
110 * @param string $target
112 public function renderTo($target)
114 $fp = @fopen($target, 'wt');
117 fwrite($fp, $this->render());
120 $error = error_get_last();
122 throw new RuntimeException(
124 'Could not write to %s: %s',
128 strpos($error['message'], ':') + 2