Macro to only print fields with data in them

Hi all, I’m trying to setup a maco which puts an if statement in front of all my table row variables to ensure they don’t print the label if they’re blank. So I have a lot of instances of the following

    {%- if row.stock -%}
    <b> Stock: </b> {{ row.stock or '' }} <br>
    {%- endif -%}

For each of the variables in my row.* list I want to call the macro to “insert” the if and the endif.

Is this possible and how would I go about it?

Thanks.

I tried the following:

{%- macro print_when(doc_field) -%}
{%- if doc_field -%}
<b> {{ doc_field }} </b>
{%- endif -%}
{%- endmacro -%}

With field defined:

{{ doc_field("row.stock") }}

But I got an error trap:

UndefinedError: ‘doc_field’ is undefined

I tried different syntax on the if:

{%- macro print_when(doc_field) -%}
{% if doc_field %}
<b> {{ doc_field }} </b>
{% endif %}
{%- endmacro -%}

Same error.

Is my syntax correct?

Thanks.

I think you should call your macro as

{{ print_when(row.stock) }}