0

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]
    }
  };
}
1
  • 1
    The javascript is going to run long after (and in a different environment) than the python. One solution might be to define a javascript array literal in the template with the contents of pic_list, and refer to than in the js function. Commented Apr 12, 2019 at 15:25

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.