I want to use the macro I defined in twig inside a controller or a module. Is that possible?

1 Answer 1


Not directly, macros can only be included from within Twig. But you can create a simple wrapper template and render that:

{# my-macro.twig #}

{% macro my_macro(foo = 'bar') %}
    <p>{{ foo }}</p>
{% endmacro %}
{# path/to/macro-wrapper.twig #}

{% from "my-macro.twig" import my_macro %}
{% set foo = foo ?? 'default' %}
{{ my_macro(foo) }}

You can use View::renderTemplate to render the wrapper template:

/** @var \craft\web\View */
$view = Craft::$app->getView();

$view->renderTemplate('path/to/macro-wrapper.twig', [
    'foo' => 'baz'
], \craft\web\View::TEMPLATE_MODE_CP);

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.