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.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

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

[SOLVED] Global functions callable from templates?


Go to End


5 Posts   2221 Views

Avatar
jizzman

Community Member, 23 Posts

3 February 2012 at 1:02am

Hi,

Sorry if this is an obvious one. I've done some searching and can't find quite what I'm after. I'm converting a template site to SilverStripe. I have a collection of global PHP functions and they are site wide. i.e. I have a helper function for constructing external links with the html. Now in SS I try:

some_page.ss
...
<p>Get your link here</p>$ExternalLink(~url~, ~link text~)
...

Which is meant to output:
<p>Get your link here</p><a class="external" href="~url~" target="_blank">~link text~</a>

I initially placed this in the Page_Controller and so Page.ss works fine. Now I've tried it on a different page type and it obviously doesn't work. In C++ I would have something like "class LinkUtils { public: static void create_external_link(...); };" and happily call "LinkUtils::create_external_link();". You get the idea. But SS?

Bashing head.

J.

Avatar
Devlin

Community Member, 344 Posts

3 February 2012 at 2:16am

If your NewPage class is a subclass of the Page class, then your public methods in Page class are available in your NewPage class too and callable via your templates.

Avatar
jizzman

Community Member, 23 Posts

4 February 2012 at 6:39pm

Edited: 04/02/2012 6:40pm

Yes, that does work. I discovered my problem was trying to call it within a <% control %> block. SS stays quiet on that one ...

Avatar
Willr

Forum Moderator, 5523 Posts

8 February 2012 at 9:29pm

Once you get inside a <% control %> you're in scope of the model record you're looping over. Not the controller class. If you put the function in class Page then it will be accessible everywhere you use page. You can also put global functions on your SiteConfig class then use $SiteConfig.Function anywhere.

Avatar
jizzman

Community Member, 23 Posts

9 February 2012 at 12:22pm

Thanks for the advice. SiteConfig looks like a cleaner option. I've currently setup an interface in Page that forwards the call to my own utility class. It's a small site so I only have a small collection of unrelated functions.