Answers.Body: <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>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-08-03T08:00:32.880Z
Answers.LastActivityDate: 2022-08-03T08:00:32.880Z
Answers.UserDisplayName: MoritzLost
Body: <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>
  
Tags: <templating><modules><controller><macro>
Title: How to use twig macro inside controller?
ThreadText: # 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:
  
  ```twig
  {# my-macro.twig #}
  
  {% macro my_macro(foo = 'bar') %}
      <p>{{ foo }}</p>
  {% endmacro %}
  
  ```
  
  ```twig
  {# 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:
  
  ```php
  /** @var \craft\web\View */
  $view = Craft::$app->getView();
  
  $view->renderTemplate('path/to/macro-wrapper.twig', [
      'foo' => 'baz'
  ], \craft\web\View::TEMPLATE_MODE_CP);
  
  ```
  
  
  ---
  
  