0

I'm using jinja2 to template a supercollider startup file.

I have a variable {{ sc_option_numOutputBusChannels }} from which I need to generate a list.

Specifically, if sc_option_numOutputBusChannels = 8, then I need to create the following list:

[0, 2, 4, 6]

for use in the line:

~dirt.start(57120, [0, 2, 4, 6]);

The function range(0, sc_option_numOutputBusChannels, 2 ) outputs that list exactly as I need it, but I've been unable to find a way to use the output of range directly as a string in my template - eg these don't work:

~dirt.start(57120, {% range(0, sc_option_numOutputBusChannels, 2 ) %} );

~dirt.start(57120, {{ range(0, sc_option_numOutputBusChannels, 2 ) }} );

Is there a way to do this?

cleary
  • 113
  • 5
  • 2
    While I was able to quickly PoC what I suspected was wrong with your code, in the future it would be helpful to include what behavior you _are_ experiencing, along with the description "these don't work" – mdaniel Mar 02 '21 at 04:08
  • Can do, thanks for the feedback (and the answer, of course!) – cleary Mar 02 '21 at 23:09

1 Answers1

3

I would guess it is because range by itself is a generator, and thus needs a consumer to indicate to ansible that you're done with the generator pipeline; the most common one I know of is | list

- debug:
    msg: ~dirt.start(57120, {{ range(0, sc_option_numOutputBusChannels, 2 ) | list }} );
mdaniel
  • 31,240
  • 5
  • 55
  • 58
  • thankyou! the concept of generators and consumers is new to me - something to look into :) – cleary Mar 02 '21 at 22:34
  • 1
    It's a carry-over from ansible+jinja2's python underpinnings: https://docs.python.org/3/glossary.html#term-generator and is _especially_ handy for things like `range` which could, in theory, generate billions and billions of items, but after filtration may only be 5 of them – mdaniel Mar 03 '21 at 06:15