corvid
corvid

Reputation: 11187

pass javascript variables into my macro in jinja2

I am trying to display a simple error message upon a $.get() failure

$.get('{{ url_for(c) }}', function(data) {
  $('#{{ chart_id }}').highcharts(data);
}).fail(function(resp) {
  {# I am not sure why this is not working as intended #}
  {% set error_html = error(resp, c)|replace('\n', '\\\n') %}
  $('#{{ chart_id }}').html('{{ error_html }}');
});

However, it does not seem that I have access to my resp object, which is a javascript variable. How does one pass that into the macro as if it were a dictionary?

Upvotes: 1

Views: 2590

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 159905

The issue is that Jinja runs before the page loads:

{# what Jinja sees #}
text ... {{ url_for(c) }} ... text ...
  text ... {{ chart_id }} ... text ...
... text ...
  {# I am not sure why this is not working as intended #}
  {% set error_html = error(resp, c)|replace('\n', '\\\n') %}
  ... text ... {{ chart_id }} ... text ... {{ error_html }} ... text ...
  {# What on earth is `resp`? #}

You don't actually want to compose this on the template level - instead, take your response and work with it in JavaScript:

.fail(function(resp) {
  var displayError = calculateDisplayErrorFromResponse(resp);
  $('#{{ chart_id }}').html(displayError);
});

Upvotes: 2

Related Questions