Using the Silverstripe TemplateParser for something else...

Using the Silverstripe TemplateParser for something else...

We are currently experimenting with Bookdown to generate the documentation for our open-source components in one central location. Obviously the generated site should have a similar look`n`feel as this blog or our website. Since both instances are powered by Silverstripe and share a theme I was curious if it is possible to use this theme within Bookdown. As it turns out, it is not that difficult ;)

First of all we need to require a few files:

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/framework/core/Constants.php';
require_once __DIR__ . '/framework/core/Core.php';

For passing data to the template parser we need to create a ViewableData instance and pass that to an SSViewer_Scope instance:

$viewableData = new ViewableData();
$scope = new SSViewer_Scope($viewableData);

To parse the Silverstripe template it is needed to instantiate an SSTemplateParser object and call the compileFile() method which takes one argument, the absolute path of the template to parse:

$parser = new SSTemplateParser();
$code = $parser->compileFile(__DIR__ . '/');

The SSTemplateParser converts the Template into valid PHP code that contains all sorts of of static method calls. To execute the code via eval() we need to strip the opening php tag first:

$code = substr($code, 5);
$val = '';
echo $val;

Passing variables to $scope is quite simple, you just need to call the setField($key, $value) method of $viewableData:

$viewableData->setField('Title', 'test');

Passing an object like SiteConfig to the $viewableData instance requires a bit more work. Since we only have the Silverstripe Framework and not the CMS installed, there is no SiteConfig class available, thus we need to create one by simply extending the ViewableData class and pass it to the $viewableData instance:

class SiteConfig extends ViewableData
    protected $Title = 'Static Site Title';

$viewableData->setField('SiteConfig', new SiteConfig());

Now the calls to $SiteConfig.Title in our templates get replaced by the title we defined in the SiteConfig class.

Tags: , ,

Eintrag von Stephan Hochdörfer am 30.12.2016

comments powered by Disqus