I am new to Craft from EE. I have a snippet of code which I will be reusing in several templates. I see Globals but that doesn't seem like like what I am looking for. What is the proper method of doing this within Craft? Thanks


Craft uses Twig, and Twig uses macros for reusing snippets of code within templates.

In your macro file (for instance, macro/userMacro.html), you can create a macro:

{% macro hairColor(user) %}
    <span class="hair-{{ user.hairColor }}">{{ user.hairColor }}</span>
{% endmacro %}

Then, in any other file (or in your main _layout template, for that matter), you can import and use this macro:

{% import "macro/userMacro" as userMacro %}

{% for user in craft.users %}
    {{ userMacro.hairColor }}
{% endfor %}

Place your import-tag at the top of your _layout file, and you will be able to use it in every template that extends it (or is included by it).

  • Thank you for your response. Where should I create the macros directory, within craft/templates directory? Feb 28 '15 at 18:22
  • Yes, within your templates folder. You can name it anything you want, though.
    – Paul
    Feb 28 '15 at 18:24
  • Okay perfect. Trying to wrap my head around this. I got an example working pretty quickly. Because I won't have many macro's, does it make sense to just have a single global macros file versus one for each snippet/macro? Feb 28 '15 at 18:44
  • For example, this is a reusable subnavigation. I just need t o pass it an entry's url. I got it working passing the entire entry but couldn't figure out just sending the entry.url. Feb 28 '15 at 18:45
  • I always have all related macros in one file. A user macro file, an image macro file and a forms macro file for example.
    – Paul
    Feb 28 '15 at 18:46

You can also do the following:

Create a file, for my purpose i created a file in


Then in my templates, I reuse the code in somefile.html by using

{{ include("_includes/somefile") }}

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.