在 HubSpot CMS 中,您可以像这样创建宏:
{% macro render_section(classes, background_style) %}
<div class="mosaic-section {{classes}}" {{background_style}}>
{{ caller() }}
</div>
{% endmacro %}
是否可以在不同的模块和模板之间共享此宏?或者您是否必须在需要使用它的任何地方重复该宏?
在 HubSpot CMS 中,您可以像这样创建宏:
{% macro render_section(classes, background_style) %}
<div class="mosaic-section {{classes}}" {{background_style}}>
{{ caller() }}
</div>
{% endmacro %}
是否可以在不同的模块和模板之间共享此宏?或者您是否必须在需要使用它的任何地方重复该宏?
是的,您可以跨模块共享宏,但仅限与包含您创建的宏的导入 HTML 部分/片段处于同一范围内的模块。
根据使用{% import %}
标签的 HubL 文档(在此处找到),可以从用户创建的 HTML 部分/片段导入宏。例如,如果您要创建以下 HTML 部分,称为macros.html
:
{% macro render_section(classes, background_style='', data='') %}
<div class="mosaic-section {{classes}}" {{background_style}} {{data}}>
{{ caller() }}
</div>
{% endmacro %}
然后,您将导入macros.html
模板,例如,homepage.html
使用以下 HubL/HTML 代码调用:
<!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>
结果,添加到homepage.html
编码模板的所有模块现在都与导入的宏在同一范围内,因此所述模块现在可以使用宏。
如果您想从包含多个宏的 HTML 部分导入单个{% from %}
宏,您可以使用标记(在此处找到)并执行以下操作:
{% from 'path/to/macros.html' import render_section %}
现在宏render_section()
可用于编码模板中的所有进行中的模块。
笔记:
不幸的是,我还没有找到一种方法来“全局”使用/导入宏到拖放模板中——至少不必使用嵌入 HubL 模块,该模块会在生成的 HTML 标记中添加奇怪的间距问题可能需要使用 CSS 解决。
希望这个答案是足够的,并有助于解决您提出的问题。