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?
-
1Do you need to specify it as a macro or would a Twig function work, too?– VictorCommented Jun 22, 2014 at 19:14
-
What are you trying to do with the macro? What purpose is it serving?– Bryan RedeagleCommented Jun 22, 2014 at 20:01
-
@VictorIn, twig functions could probably work, however it doesn't feel right having several lines of markup within PHP classes....– Christopher ManciniCommented Jun 22, 2014 at 20:29
-
@ChrisMancini Can you add an example of what you are trying to do to your question?– VictorCommented Jun 22, 2014 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 ManciniCommented Jun 22, 2014 at 20:31
1 Answer
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. :-/ Commented Jun 23, 2014 at 1:41
-
My bad. I added a couple commands that will allow the plugin to find the macro template for rendering. Commented Jun 23, 2014 at 2:04