Skip to content

Commit 4646575

Browse files
committed
its now possible to provide a string template
1 parent 4cc317c commit 4646575

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

readme.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -175,10 +175,10 @@ params can be encapsulated into `|` characters if your expression contains `,`
175175
## Class
176176

177177
```php
178-
new Le\Dataplater\Dataplater(string $template, array $vars)
178+
new Le\Dataplater\Dataplater(?string $filename, ?string $template, array $vars)
179179
```
180180

181-
when creating an object, pass your template filename as the first constructor parameter. the second parameter is optional and can hold global variables that will be made available to each render of the template.
181+
when creating an object, pass your template filename as the first constructor parameter. if you instead want to load template HTML from a string, skip the first argument by using named arguments (e.g. `template: $htmlString`). when you want to define global vars, pass them to the argument vars (e.g. `vars: $globalVariables`).
182182

183183
```php
184184
$dataplater->render(array $vars);

src/Dataplater.php

+13-4
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,25 @@ class Dataplater
1515
* @throws Exception
1616
*/
1717
public function __construct(
18-
string $filename,
18+
?string $filename = null,
19+
?string $template = null,
1920
public array $vars = []
2021
)
2122
{
22-
if(!file_exists($filename)) throw new Exception('template file not found');
23-
$html = file_get_contents($filename);
23+
if($filename === null && $template === null)
24+
throw new Exception('must provide either the filename or the template string param');
25+
26+
if($filename !== null && $template !== null)
27+
throw new Exception('you can either pass the filename or template string params, not both');
28+
29+
if($filename !== null) {
30+
if (!file_exists($filename)) throw new Exception('template file not found');
31+
$template = file_get_contents($filename);
32+
}
2433

2534
libxml_use_internal_errors(true);
2635
$this->doc = new DOMDocument();
27-
$this->doc->loadHTML($html);
36+
$this->doc->loadHTML($template);
2837
$this->xpath = new DOMXpath($this->doc);
2938

3039
$this->defineBuiltInFunctions();

0 commit comments

Comments
 (0)