2017-02-18 1013 views
0

我想动态过滤烧瓶生成的表格,这要归功于来自另一个类似表格的JavaScript设置的变量。Flask jinja2表格生成变量

不幸的是,Javascript变量似乎不能在Jinja2上下文中重用(因为jinja2上下文在Javascript之前运行)。

在下面的例子中,我想用project_id过滤任务。这个project_id是由于在另一个表中选择的值而设置的。

注意:我想避免因为此解决方案而重新加载页面。

{% for Task in mytasks %} 
    {% if Task.project_id == var_project_id %} <- Not working, the javascript variable is not recognized 
     <tr class="clickable-row"> 
     <td style="display:none;"> {{ Task.task_id }} </td> 
     <td style="display:none;"> {{ Task.project_id }} </td> 
     <td>{{ Task.title }}</td> 
     <td class="task_description" > {{ Task.description }} </td> 
     <td class="task_creation_date"> {{ Task.creation_date }} </td> 
     </tr> 
    {% endfor %} 
+0

你忘了问一个实际问题。另外AFAIK Jinja在服务器端处理(而JavaScript运行在客户端) - 所以你需要使用基于JavaScript的东西(无论是香草JS,jQuery还是完整的前端框架) – UnholySheep

+0

非常感谢UnholySheep,它更清晰现在。你有任何在Bootstrap中使用悬浮表的例子吗? – nico59128

回答

0

我已经找到了解决方案由于采用了简单的JavaScript函数。

这里吧,以防万一别的人有同样的问题:

<script>  
//The project id is defined when the project is selected in a hover table 
$('#myTableProject tbody tr').click(function (event) { 
$('tr').not(this).removeClass('highlight'); 
$(this).addClass('highlight'); 
project_id = $(this).find('td.project_id').text(); 
//... 
var tableTasks; 
tableTasks = document.getElementById("myTableTasks"); 
tr = tableTasks.getElementsByTagName("tr"); 
// Loop through all table rows, and hide those who don't match the search query 
for (i = 0; i < tr.length; i++) { 
td = tr[i].getElementsByTagName("td")[1];// [1] is the column number you want to filter 
if (td) { 
    //each cell of the column [1] is compared to the project id 
    if (td.innerHTML.toUpperCase().indexOf(project_id) > -1) { 
    tr[i].style.display = "";//the data is displayed 
    } else { 
    tr[i].style.display = "none";//the data is hidden 
    } 
} } 
</script> 

更多信息: https://www.w3schools.com/howto/howto_js_filter_table.asp