Twig icon indicating copy to clipboard operation
Twig copied to clipboard

Call Macro from PHP

Open asnyder opened this issue 12 years ago • 4 comments

It would be nice to call a macro from PHP.

For example, I might have a message macro that renders an individual message row when called macro.message(....).

Now, in my twig templates I would call like above. However, in certain cases, specifically in REST based cases. I might want to do the equivalent of:

    foreach($messages as $message)
    {
        $response .= $twig->renderMacro('macros/message.macro.twig', message, $args); // $args could be an array of args, or even actual .... args so that it's a straight pass through as if they were calling the macro directly from PHP.
    }
    return new Response($response);

As far as I know, in order to do this one would have to create a page like the following:

{% import "macros/messages.macro.twig" as message_macro %}

 {{ message_macro.message(_context, loop.index0, message.username, [assets.profile_path, '/', message.path]|join, message.formatted, true) }}

and then call render normally. This seem extraneous and unnecessary.

asnyder avatar Dec 20 '13 21:12 asnyder

I agree ...

rico avatar Jul 20 '14 13:07 rico

Twig only provides a way to render templates from PHP. Everything else (including macros) are not exposed via a public API as it would limit our ability to refactor the implementation. We try very hard to not break BC and the clear separation between PHP and Twig is a feature. Add to that that macros are probably going to be heavily refactored in the next major version. So, it won't happen. Sorry.

fabpot avatar Aug 01 '14 07:08 fabpot

Fair enough - thanks for the detailed answer, and your work.

rico avatar Aug 01 '14 08:08 rico

Thank you for the reply, but building modules in macros is one of its primary purposes. Furthermore, it's a common design pattern to return partials via AJAX. So forcing someone to create a hack template that simply calls the macro is a completely unnecessary extra step.

I don't understand why you feel this changes the separation. I believe the separation is still there. If you implement TWIG manually, you have to call the render function on a template. Similarly, one should be able to do the same thing but with a macro function. It's just as separate. In both cases you're calling a function that returns a string that you're rendering.

asnyder avatar Aug 01 '14 16:08 asnyder