将javascript变量传递给jinja2中的宏

时间:2014-06-09 15:32:29

标签: flask jinja2

我试图在$.get()失败时显示一条简单的错误消息

$.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 }}');
});

但是,我似乎无法访问我的resp对象,这是一个javascript变量。如何将它传递到宏中,好像它是一个字典?

1 个答案:

答案 0 :(得分:2)

问题是Jinja在页面加载之前运行:

{# 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`? #}

您实际上并不想在模板级别上撰写此内容 - 而是采取您的回复并在JavaScript中使用它:

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