在jinja2中传递javascript变量到我的宏中 [英] pass javascript variables into my macro in jinja2

查看:323
本文介绍了在jinja2中传递javascript变量到我的宏中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ < > $。get('{{url_for(c)}}',function(data){
$('#{{chart_id}}')。highcharts(data);
$}}。失败(函数(resp){
{#我不知道为什么这不是按预期工作#}
{%set error_html = error(resp,c)| replace(' ('{{error_html}}');
}) ;

但是,我没有访问我的 resp object,这是一个javascript变量。如何将它传递到宏,就像它是一个字典?

解决方案

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

  {#Jinja看到#} 
文字... {{url_for(c)}} 。text ...
text ... {{chart_id}} ... text ...
... text ...
{#我不确定为什么这不是按预期工作#}
{%set error_html = error(resp,c)| replace('\ n','\\\\')%}
... text。 .. {{chart_id}} ... text ... {{error_html}} ... text ...
{#什么是'resp`? #}

您实际上并不想在模板级别编写这个代码 - 取而代之的是,并在JavaScript中使用它:

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


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?

解决方案

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);
});

这篇关于在jinja2中传递javascript变量到我的宏中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆