Search code examples
djangosvgdjango-templates

Django template svg rendering issue


I have a django html template that contains this svg element:

<svg id="tower_layout" width="400" height="400" style="border: 1px solid black;" xmlns="http://www.w3.org/2000/svg">
  <rect width="398" height="398" x="1" y="1" fill="#e4e4e7" />
  <text x="200" y="20" stroke="black" font-size="15" text-anchor="middle">Tower Diagram</text>
  {% for i in val_range %}
    {% if i > 0 %}
    <line x1="{{ val[i-1].x_d }}" y1="{{ val[i-1].y_d }}" x2="{{ val[i].x_d }}" 
      y2="{{ val[i].y_d }}" stroke-width="1" stroke="black" />
    {% endif %}
  {% endfor %}

I'm receiving "TemplateSyntaxError: Could not parse the remainder: '[i-1].x_d' from 'val[i-1].x_d'" when I try to render the template. I've paused the template and verified that all 4 val items are available using the debug console. I'm baffled as to the cause of this error.

Any suggestions would be much appreciated!


Solution

  • You can't use use this in your Django templates:

    {{ val[i-1].x_d }}
    

    You'll need to create a custom tag or a filter to access values inside val, which I believe is some dict.

    See https://docs.djangoproject.com/en/5.0/howto/custom-template-tags/