TransWikia.com

DRY variable setting across templates (macro for variable?)

Craft CMS Asked on October 3, 2021

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?

One Answer

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.

Answered by Lindsey D on October 3, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP