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?
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 calledmacros.html
:You would then import
macros.html
into a template, for example, calledhomepage.html
with the following HubL/HTML code: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: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.