silverlight-4.0silverstripe

How can I pass content to a parent template from a child template in Silverstripe


I want to pass some content from a elemental block up to a parent template (to change the page header) - Is this possible? I don't have any example code for what I'm trying because I don't have any idea how to implement it.

This would be similar to the content_for facility in Rails / ERB templates.

Parent:

Page Title <%= yield :title %>

Child Template:

<% content_for :title do %>
  <b>, A simple page</b>
<% end %>

Is there anything like this or some other way to do this in SS templates?


Solution

  • Silverstripe Templates are a one-way street - you can't pass values upstream.

    What you can do in this case is add a method to the page object to fetch the correct title from the block:

    public function getTitleForTemplate()
    {
      return $this->MyBlock->PageTitle;
    }
    

    And then in your template you can simply call that method or as in this example treat it like a property:

    Page Title $TitleForTemplate
    

    If you want to use a template to render out this property (e.g. if you have different styling or markup for different blocks which belong to different pages) you can render the template in that method. There are many ways to do this but perhaps the most sensible would be to call renderWith() on the block object:

    public function getTitleForTemplate()
    {
      return $this->MyBlock->renderWith(['type' => 'Includes', 'templates' => ['MyBlockTitle']);
    }
    

    and then have a template in your theme's templates/Includes directory called MyBlockTitle.ss which renders out the title with any styling and markup you need for it.

    In other words: data belongs in models, the template is just there to display that data. So if you need some specific data to be displayed in the page template, the page object should have that data available.

    Disclaimer: I haven't tested this code, it was done from memory. Some of the syntax especially for the second example may be slightly different in reality.