How to include long chunks of code that are used several places

Like many others I am working with market prices and in my case adding grid fees and taxes. For this I use the following code:

  • sensor:
    • name: “xxx”
      state: >
      {{ 0 }}
      attributes:
      tot_prices: >
      {% set ns = namespace(prices=) -%}
      {%- set day = state_attr(‘sensor.nordpool_kwh_trheim_nok_3_10_025’,‘raw_today’) -%}
      {%- long chunk of code -%}

      {%- set day = state_attr('sensor.nordpool_kwh_trheim_nok_3_10_025','raw_tomorrow') -%}
      {%- if state_attr('sensor.nordpool_kwh_trheim_nok_3_10_025','tomorrow_valid') -%}
        {%- same long chunk of code -%}
        
      {%- endif -%}
      

I simplified and left out a lot. The code is working fine. However, I would like to place the “long chunk of code” in another file or use some other technique to avoid having the same sequence twice. I have been experimenting with & and * and with !include, but I’m not able to find anything that works in this particular context.
I can live with this but would like to understand how to handle this as it will be a recurring issue.

Greetings from an old Fortran programmer used to “subroutines”

There’s a bit in the docs about reusing templates:

See number 11 here:

Well, sorry, I forgot to mention this, seemed obvious to me, but it was actually a Home Assistant question.

Thanks a lot, this did the trick:

{% from ‘xxx.jinja’ import my_macro with context %}
{{ my_macro }}