HubSpot macros are like personal cheat codes designed to make your life as a developer easier. USE THEM!

If you find yourself writing the same chunks of code time and time again it's likely that you're making your life much more difficult than it needs to be. HubSpot macros to the rescue!

What is a HubSpot Macro?

Easy, HubSpot macros are basically custom, lite, functions. I say lite because the hubl language itself, being a templating language, is a bit limitting; however, with some creativity you can get quite far with the power of macros on your side.

Basic Macro Syntax

{# create your macro #}
{% macro my_macro_name(arg1, arg2) %}
{% endmacro %}

{# to consume your macro #}
{{ my_macro_name('DevBeej', 'Is a HubSpot Expert' )}}

The former code will result in the following output

   <h2>Is a HubSpot Expert</h2>
   {# Dont worry, if you dont feel like one yet, you will be one soon! #}

Where can I use Macros?

HubSpot Macros can be used anywhere where hubl is valid syntax. This primarily means in CSS files (not module.css), in HTML/Hubl files (module.html included), in templates, and in template partials.

Practical Examples

Convert CSS Hex to RGBA in CSS

{%- macro to_rgba(hex, opacity) -%}
   rgba({{hex|convert_rgb}},{{ opacity / 100) }};
{% endmacro %}

{# further in css file #}
.css-selector {
   background-color: {{to_rgba('#ffffff', 90 )}}
.overlay {
   background-color:  {{to_rgba('#000000', 50 )}}

Toggle Sections of Code in Module

{%- macro build_intro_one() -%}
   <section class="header">
      {# intro-1 Content #}
{% endmacro %}

{%- macro build_intro_two() -%}
   <section class="header">
      {# intro-2 Content #}
{% endmacro %}

{%- macro build_main() -%}
   <main class="header">
      {# main Content #}
{% endmacro %}

   will build a different intro section depending 
   on what value the user selects in the boolean field.
<section class="body-wrapper">
 {{ build_intro_one() if module.boolean == true }}
 {{ build_intro_two() if module.boolean == false }}
 {{ build_main() }}