<p>Not directly, macros can only be included from within Twig. But you can create a simple wrapper template and render that:</p>
<pre class="lang-twig prettyprint-override"><code>{# my-macro.twig #}

{% macro my_macro(foo = 'bar') %}
    &lt;p&gt;{{ foo }}&lt;/p&gt;
{% endmacro %}
</code></pre>
<pre class="lang-twig prettyprint-override"><code>{# path/to/macro-wrapper.twig #}

{% from &quot;my-macro.twig&quot; import my_macro %}
{% set foo = foo ?? 'default' %}
{{ my_macro(foo) }}
</code></pre>
<p>You can use <code>View::renderTemplate</code> to render the wrapper template:</p>
<pre class="lang-php prettyprint-override"><code>/** @var \craft\web\View */
$view = Craft::$app-&gt;getView();

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

CC BY-SA 4.0
2022-08-03T08:00:32.880Z
2022-08-03T08:00:32.880Z
MoritzLost
<p>I want to use the <code>macro</code> I defined in <code>twig</code> inside a <code>controller</code> or a <code>module</code>.
Is that possible?</p>

<templating><modules><controller><macro>
How to use twig macro inside controller?
# How to use twig macro inside controller?

(Asked by: username_0 on 2022-08-03)

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

**Tags:** templating, modules, controller, macro

---

## 1 answers

### Answer by username_1 on 2022-08-03. Score: 1 | Accepted answer

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') %}
    {{ foo }}
{% 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);


---

