Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Themes

Discuss SilverStripe Themes.

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

SS3 (3.02) SOLVED how to use custom php classes in templates


Reply

5 Posts   1032 Views

Avatar
nantoga

25 October 2012 at 10:27am (Last edited: 25 October 2012 10:29am), Community Member, 6 Posts

Hello,

I would like to use a custom class in a template. As far as I could find out, one needs to do the following:

1. Store the custom class in the mysite folder:

mysite/customcode/TestClass.php

Next, Silverstripe should automatically load those classes as far as I understood the help pages:

2. Class itself:
---

class TestClass {

function showMeSomething() {
$output = "I am a test message";
return $output;
}

} // end class TestClass

---

3. Template

I tried many ways:

$showMeSomething

<% control TestClass %>
$showMeSomething
<% end_control %>

---

What am I misunderstanding? How can I run my own classes within templates?

Do I have to attach it to an silverstripe object (extend class) --> what would be the most basic class to extend and how can I access the methods?

Do I need to create a controller class additionally --> how would I access the controller then?

Your help will be very appreciated!

Best wishes, A.

Avatar
jbridson

25 October 2012 at 1:41pm Community Member, 7 Posts

Hey there,

You might want to take a look at the template documentation on [url=http://doc.silverstripe.org/framework/en/reference/templates#custom-template-variables-and-controls]Custom Template Variables and Controls[/url].

I hope this helps.

Avatar
nantoga

25 October 2012 at 9:33pm Community Member, 6 Posts

@jbridson

Yes, I am aware of this article and I fully understand the integration of classes within the ›Framework‹.

My question is nevertheless still open: I would like to know how I can use my own classes within templates without using the Page Class.

Maybe that's not possible. That's what I want to know.

If it is not possible, I would like to know if there is a more ›primitive Silverstripe Class‹ I could use. Or does it have to be the Page Class?

Whatever, I couldn't find a clear article in the Help Section about this topic at all.

If somebody can help - it will be truly appreciated!

Best wishes, A.

Avatar
lx

26 October 2012 at 12:07am Community Member, 83 Posts

hi nantoga,

i would do it roughly like this:

in .ss

<div style="background: red;">
$showit.Text
</div>

in page_controller:

public function showit() {
$t = new TestClass();
$text = $t->showMeSomething();
return new ArrayData(array("Text" => $text));
}

I hope that this works.

Avatar
nantoga

31 October 2012 at 1:35pm Community Member, 6 Posts

Thx! That helps to understand the usage of custom code within silverstripe