2017-02-18 1016 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