I'd like to run the entry.body content through some PHP functions before the template outputs it, there probably two approaches to this:

  1. Create a twig function via Plug (if possible) and use that in template like:

    {{ MyFunction( entry.body ) }}
  2. Have function automatically grab the "body" of the current page, run through functions, and update it before template runs it. I'd prefer this method although but have no clue how to go about it.

What would be the best approach -- and does anyone have any pointers / samples on how it'd be done? I've been digging through documentation but am struggling to find how to get the current entry.body through a plugin, or how to update it (just for the page rendering + template, not in database.)


There is no event or hook that I'm aware of that can intercept the template rendering process directly. You would likely need to instigate this from within your template. I would suggest perhaps using a plugin variable either directly, or as a wrapper for your plugin service method (if you need to do something more complicated).

Something like the following:

Note: This is adapted from the 'BusinessLogicTemplate' plugin which provides a great starting point for plugin development.

<?php namespace Craft;

class MyPluginVariable

     * Whatever you want to output to a Twig tempate
     * can go into a Variable method.
     * HOW TO USE IT
     * From any Twig template, call it like this:
     *     {{ craft.myPlugin.exampleVariable }}
     * Or, if your variable requires input from Twig:
     *     {{ craft.myPlugin.exampleVariable(twigValue) }}
    public function exampleVariable($optional = null)
        return "And away we go to the Twig template...";
    public function formatBody($body)
        /* process $body and return it to the template */
        return $body;


Then in your template:

{{ craft.myPlugin.formatBody(entry.body) }}
  • This is EXACTLY the kind of functionality I was looking for. Works perfect! Thank you x100000000 – taylor Jan 28 '15 at 23:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.