How can I render an Include (.ss) file to a template variable, from within a module?

Silverstripe Version 5:

Question:
Hi there,

I’m trying to render a .ss file to a template variable from within a module through a controller extension . e.g:

 vendor/vendor_name/module_name/templates/Includes/test_include_file.ss
namespace vendor\name_space;
use SilverStripe\Core\Extension;
class TestControllerExtension extends Extension
{
    protected function onAfterInit()
    {
         $this->owner->customise([
            'TemplateVariable' => '/vendor_name/module_name/templates/test_include_file'
         ]);
     // ....

Is this the correct approach?

Thanks in advance,
James

You should probably just use <% include test_include_file %> inside your template instead.

The documentation for include is at https://docs.silverstripe.org/en/developer_guides/templates/syntax/#includes

Thanks Guy, I understand. I guess if I’m going to include instructions to add a template variable, I might as well just do that with the include.

One quick question. Is it possible to reference an Include file (located in a module), without having to move the file to the app/templates/vendor_name/module_name/templates/Includes/... directory?

For example, in say app/templates/Page.ss

<% include vendor_name/module_name/templates/test_include_file %> ?

Got it, read the docs. For anyone else in the future. Use the namespace not the directory path.

1 Like

When I have needed to render an include to a variable (say, for an ajax/json response) I have done:

‘html’ => $this->customise($data)->renderWith(‘Includes/Results’)->__toString()

1 Like