0

I'm using a for loop to create a list like [1, 2, 3]. Here's my Jinja template, which produce some Javascript:

xAxis: {
                categories: {
                    [
                    {% for data in records['result'] %}
                        {{ data['_id']['day'] }},
                    {% endfor %}
                ]
            },

It runs fine and generates the expected result, but my IDE (PyCharm) complains that the final comma is unnecessary (it isn't): [1,2,3,] instead of [1,2,3].

Is there a better way to place a comma at end end (e.g. convert to string first and concatenate the comma to the end)? Or, should I ignore the warning?

Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
okoboko
  • 4,332
  • 8
  • 40
  • 67
  • 1
    Please, do mind, that others do not have the context of your problem in their heads as you do and pay attention to details. What is your code? Is is definitely not Python, it looks like some jinja2 or Django template, but a bit strange. – Jan Vlcinsky Jun 11 '14 at 14:58
  • i would use a the `join` filter rather than a loop for this – njzk2 Jun 11 '14 at 15:00
  • Is this not a duplicate of http://stackoverflow.com/questions/11974318/how-to-output-a-comma-delimited-list-in-jinja-python-template – dalore Jan 22 '16 at 10:57

1 Answers1

2

If you are using Jinja (it seems to be the case), you can use the join filter directly:

xAxis: {
            categories: {
                [{{ records['result']|join(', ', attribute='_id.day') }}]
        },

The attribute syntax allows to get subkey by separating them with a dot, according to the source code.

Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
  • Perfect! Works great -- didn't know about `attribute`. Thanks! :) – okoboko Jun 11 '14 at 15:03
  • If I want to join attributes `_id.month` and `_id.day` to generate a list like `[1/1, 1/2]`, how come I can't do this? `[{{ records['result']|join(', ', join(attribute='_id.month', attribute='_id.day')) }}]` – okoboko Jun 12 '14 at 16:52
  • You can't do it "simply" with templates. You should review your `records` data structure to include a way to get the `_id.day+"/"+id._month` directly. – Maxime Lorant Jun 12 '14 at 17:08