Mike C.
Mike C.

Reputation: 1921

Is it possible use a Javascript variable as an index for a Python List in a Flask Template?

On the last line is pic_list is the python list. Is it possible to index the Python list using a javascript variable within a Flask Jinja2 template?

function moveright(cur_pos, list_length) {
  if (current_position !== -9999) {
    current_position = cur_pos;
  }
  if (current_position < list_length - 1) {
    current_position = current_position + 1;
  } else {
    current_position = 0;
  }
  document.getElementById('image').src = {
    {
      pic_list[current_position]
    }
  };
}

Upvotes: 0

Views: 91

Answers (1)

Gabe
Gabe

Reputation: 995

I'm not sure I understand the question. Why don't you try to pass the Python list over to JavaScript by converting the collection into a JSON string?

1.Use the json.dumps() method to convert the list into a JSON string.

@app.route('/test')
def custom_view():
    pic_list = ['banana', 'orange', 'apple']
    return render_template('index.html', data=json.dumps(pic_list))

2.Pass the JSON string to the template

<script>
    console.log({{ data|safe }});
</script>

You SHOULD AVOID this procedure if the collection contains user-supplied data.

Upvotes: 1

Related Questions