1

I have a need for something like the following:

{# Template A #}
    {# Do X that sets variable x #}
    {# Do Y that sets variable y #}
    {# Pass x and y into A include partials #}

{# Template B #}
    {# Do X that sets variable x #}
    {# Do Y that sets variable y #}
    {# Pass x and y into B include partials #}

The logic for X and Y is the same in templates A and B.

Is there a way to write each once in some kind of dedicated partial and place them in templates A and B, something akin to return in a JavaScript function?

I'm not sure there is. I think that macros only produce front-end output. And so I have to duplicate the logic in each template. Is that right?

5
  • How good are your PHP skills?
    – Lindsey D
    Commented Jul 29, 2020 at 20:59
  • Hi Lindsey. Not great. Is this plugin territory? Commented Jul 30, 2020 at 10:59
  • Not necessarily, though it would be a reasonable solution. You can probably pull this off in raw Twig as well.
    – Lindsey D
    Commented Jul 30, 2020 at 13:55
  • Ok. Am I right that you can’t use a Macro to change the state/contents of a variable – e.g. a hash – because a Macro is predicated on generating markup? If yes, is there another technique? Commented Jul 30, 2020 at 15:18
  • 1
    Have just found Robin Schambach’s 2017 answer to Use a Twig macro to set a variable. I note that Twig perversion provides a return scope, which I think is what I need, but I’m nervous about relying on a third party plugin for this. Would be great if it were native to Craft. Commented Jul 30, 2020 at 15:33

1 Answer 1

2

As you noted in your comment, the Twig Perversion plugin will do exactly what you need. It allows you to return a value from a macro, which isn't typically something that Twig permits.

Personally, I'd consider it to be fairly safe to rely on this plugin for a few reasons. Marion is a long-standing and trusted developer in the community, the plugin is relatively simple, and could easily be replaced with a small custom module if it ever went defunct. It also doesn't touch your data, so removing it in the future won't cause any problems.

1
  • 2
    Twig Perversion relies on twig not changing drastically, which is a reasonably safe assumption. Commented Jul 30, 2020 at 19:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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