This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.
Hi,
Firstly, My apologies if this has been asked previously but I could find a similar question, if there is one, please by all means point me to it.
I am pretty much a newbie to October CMS and have a question about custom PHP within a page, specifically within the 'code' section (either through the frontend editor or between the double equals in the file itself)
I have been testing and learning various features using the support and tutorials given on the site and know that built in functions such as 'onStart()' and 'onEnd()' can be created.
But can I create a custom function and call it from within the page itself?
This wouldn't be a common practice for me but during learning I find it helps to learn in small steps!
example: In the 'code' section (or within the douple equals)
function testFunc($var) {
echo $var
}
within the 'Markup' Section
{{ testFunc("some string") }}
i would expect the function to output the value of $var as "some string"
But what I actually get is an exception that says unknown function 'testFunc()'
Would I have to create a simple plugin that would allow me to create small functions to allow me to test small functions and therefore take small steps rather than jump in with both feet and have to create a plugin just for a single instance of a code call?
Hey,
Don't think your example is possible from the PHP section on page, although still relatively new to October myself so may be wrong.
You could pre-process your variables, e.g:
function testFunc($var) {
return $var;
}
function onStart()
{
$this['foo'] = $this->testFunc("some string");
}
?>
==
{{ foo }}
Alternatively as you mentioned, you could create a plugin and add your own Twig functions (https://octobercms.com/docs/plugin/registration#extending-twig)
Ok
So after a bit of thinking, I reaslised that this wouldnt work, the reason being that the PHP has already been an executed any functions within the 'Code' section of the site before it gets to any function calls within the markup, so if I create a function in Code, then write a call for that function at the bottom of the markup page, then the function will never be called correctly because as far as the CMS is concerned there is no more PHP to do, so when it comes across a call for a function (even if it has already been defined) then the PHP section has been completed and the function is no longer defined.
Anyway I am going to move onto Plugins to try and play in a sandbox there :)
Thanks anyway
You can define functions in the theme code section with Anonymous Class, but they are only working on PHP7:
// in Code
function onStart()
{
// Anonymous Class only working on PHP7
$this['code'] = new class {
public function foo() {
return 'Hello World!';
}
};
}
{# in twig Markup #}
{{ code.foo() }}
Last updated
1-5 of 5