Yes helper functions like this can be included using a separate php like in the head.inc and used throughout your templates.
I extracted this function from a module I have for a project. This module has various helper function and then I load it in the templates. It's much the same as if I would include a php with functions and just personal preference.
For example:
$helpers = $modules->get("TemplateHelpers");
then use it like this where I need it.
echo $helpers->wordLimiter($page->body);
I'm not sure what you mean by applying the function to the body. I use this function to create teaser texts that are limited, and show the complete body only on the detail page.
Of course you could modify the body output, that every time you do an echo $page->body, it will run it through a function, but I'm not sure this is a good practice.
This using a hook on the formatValue of textfields would do it: (directly in template like a include, or by making it a module)
function wordLimiter(HookEvent $event){
$field = $event->argumentsByName('field');
if($field->name != 'body') return;
$str = $event->return;
$limit = 150;
$endstr = ' …';
$str = strip_tags($str);
if(strlen($str) <= $limit) return;
$out = substr($str, 0, $limit);
$pos = strrpos($out, " ");
if ($pos>0) {
$out = substr($out, 0, $pos);
}
return $event->return = $out .= $endstr;
}
wire()->addHookAfter("FieldtypeTextarea::formatValue", null, "wordLimiter");
// now this will trigger the above hook
echo $page->body;
But it's a little cumbersome, as you can't set the limit. Also this strips tags and on HTML text you'll lose formatting. But just to show adn example what is possible.
From your post I guess you like to do something like:
echo $page->body->limit(150); // not possible
It's not possible to do this, because the $page->body, body is just a string and not an object you could add methods to it.
But something like the following would be possible using hooks.
echo $page->wordLimiter("body", 120);
You can use addHook to add a method wordLimiter to page:
function wordLimiter(HookEvent $event){
$field = $event->arguments[0]; // first argument
$limit = $event->arguments[1];
$endstr = isset($event->arguments[2]) ? $event->arguments[2] : ' …';
$page = $event->object; // the page
$str = $page->get($field);
$str = strip_tags($str);
if(strlen($str) <= $limit) return;
$out = substr($str, 0, $limit);
$pos = strrpos($out, " ");
if ($pos>0) {
$out = substr($out, 0, $pos);
}
return $event->return = $out .= $endstr;
}
// this will add a custom method to Page object
wire()->addHook("Page::wordLimiter", null, "wordLimiter");
// now you can do this
echo $page->wordLimiter("body", 100);
// or this
echo $page->wordLimiter("summary", 100);