5

I have a plugin that I am writing and I want to make available a macro that can be used within the front end sites templates. What is the best way to do that?

  • 1
    Do you need to specify it as a macro or would a Twig function work, too? – Victor In Jun 22 '14 at 19:14
  • What are you trying to do with the macro? What purpose is it serving? – Bryan Redeagle Jun 22 '14 at 20:01
  • @VictorIn, twig functions could probably work, however it doesn't feel right having several lines of markup within PHP classes.... – Christopher Mancini Jun 22 '14 at 20:29
  • @ChrisMancini Can you add an example of what you are trying to do to your question? – Victor In Jun 22 '14 at 20:31
  • 1
    @BryanRedeagle, I see many use cases for this sort of functionality, but my first use case is for forms that need to be submitted that are core to my plugins functionality. The end user could invoke the macro passing through a few required / optional parameters and it renders accordingly. Similar to how we can use Craft form macros within our plugins CP. – Christopher Mancini Jun 22 '14 at 20:31
4

I'm not aware of this being possible. The control panel uses a different template path than the front end. This makes plugin templates generally inaccessible. One possible option is to create a template variable that runs a macro or renders a template on behalf of the user. Something like:

{{ craft.pluginHandle.macro(arguments) }}

You will need to make sure that the template path is set to the Control Panel so that your macro can be found, and that it's set back afterwards. At the start of the function set this:

craft()->path->setTemplatesPath(craft()->path->getCpTemplatesPath())

Then when you are done rendering your macro (preferably to a variable to return later), you set it back:

craft()->path->setTemplatesPath(craft()->path->getSiteTemplatesPath())

  • So, I just attempted this, but renderMacro seems to only have access to the front end template path, even when doing it through template vars. :-/ – Christopher Mancini Jun 23 '14 at 1:41
  • My bad. I added a couple commands that will allow the plugin to find the macro template for rendering. – Bryan Redeagle Jun 23 '14 at 2:04

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.