Search code examples
hublhubspot-cms

Is it possible to share HubL macros across modules and templates?


In the HubSpot CMS, you can create a macro like so:

{% macro render_section(classes, background_style) %}
    <div class="mosaic-section {{classes}}" {{background_style}}>
        {{ caller() }}
    </div>
{% endmacro %}

Is it possible to share this macro across different modules and templates? Or do you have to repeat the macro everywhere you need to use it?


Solution

  • Yes, you can share macros across modules but only the modules that are in the same scope as an imported HTML partial/snippet that contains the macros you've created.

    According to the HubL docs for using the {% import %} tag (found here), macros can be imported from user created HTML partials/snippets. For example, if you were to create the following HTML partial called macros.html:

    {% macro render_section(classes, background_style='', data='') %}
        <div class="mosaic-section {{classes}}" {{background_style}} {{data}}>
            {{ caller() }}
        </div>
    {% endmacro %}
    

    You would then import macros.html into a template, for example, called homepage.html with the following HubL/HTML code:

    <!doctype html>
    <head>
        {# standard HubL header code goes here %}
    </head>
    <body class="site-page two-column {{ builtin_body_classes }}" style="">
    
        {% import 'path/to/macros.html as module_macros %}
    
        <!--- more HubL/HTML code .... -->
    
        {{ standard_footer_includes }}
    </body>
    </html>
    

    And as result, all modules added to the homepage.html coded template are now in the same scope as the imported macros and as such said modules can now utilize the macros.

    If you'd like to import a single macro from a HTML partial that contains multiple macros you can use the {% from %} tag (found here) and perform the following:

    {% from 'path/to/macros.html' import render_section %}
    

    Now the macro render_section() is available to all proceeding modules in the coded template.

    NOTE:

    Unfortunately, I have yet to find a way to use/import macros "globally" into a drag-and-drop template -- at least without having to use an embed HubL module which can add weird spacing issues in the generated HTML markup that you may need to resolve using CSS.

    Hope this answer was sufficient and helps resolve the problem you've posed.