Sometimes, you will want the content that appears in your template to be slightly different from the content entered into the CMS.
For example, you might want to let your author position a dynamic element, such as a paypal button, by entering a special token such as $Paypal into the content.
What we need to do then is to load the content. Look through it for the token ($Paypal) and replace it with something else. Luckily in PHP its simple
str_replace('$Paypal', $this->PaypalButton(), $this->Content);
How do we get the template to use this as the content, without affecting the CMS? We define a method called Content() in the Page.php file in the Page_Controller class.
function Content() { return str_replace('$Paypal', $this->PaypalButton(), $this->Content); } // see the $this->PaypalButton() string up 2 lines? well that calls the Paypal() method below function PaypalButton() { return "This could be HTML/Text/Images or PHP"; }
This technique of creating a function the same name as a field can be used to set up special behaviour for a field when it is referenced within a template.
You can also extend this idea and include a whole separate template by using renderWith()
function Content() { return str_replace('$Paypal', $this->PaypalButton(), $this->Content); } // see the $this->PaypalButton() string up 2 lines? well that calls the Paypal() method below function PaypalButton() { return $this->renderWith("Paypal"); }
themes/blackcandy/templates/Includes/Paypal.ss
<p>This could be HTML/Text/Images or PHP</p>
Please use comments for notes, tips and corrections about the described
functionality.
Use the Silverstripe Forum to
ask questions.