首页 > 解决方案 > 将python对象绑定到html按钮

问题描述

我有一个创建按钮列表的python字典,即

recipes = {0 : {'name' : 'Chicken Ticka', 'products' : products_dict, 'instructions' : 'this are the instructions'},
                    1 : {'name' : 'Beef Masala', 'products' : products_dict_2, 'instructions' : 'this are the instructions for 2'}}

在 HTML 中:

{% if recipes is not none%}
            {% for key, value in recipes.items() %}
            <button type="button" class="btn btn-light btn-block">{{value['name']}}</button>
            {% endfor %}
            {% endif %}

我想根据按下的按钮以某种方式更新(通过刷新或动态)页面。
我知道如何将按钮附加到 JS 函数,但是如何将该函数与相应的对象附加?

标签: javascriptpythonflask

解决方案


这不完全是我想到的方法,但我设法获得了我想要的功能:
字典示例:

products_dict = {0 : {'name' : '123', 'count' : '234'},1 : {'name' : '345', 'count' : '456'},2 : {'name' : '567', 'count' : '678'}}
    products_dict_2 = {0 : {'name' : 'bbb', 'count' : 'qwe'},1 : {'name' : 'wer', 'count' : 'ert'},2 : {'name' : 'rty', 'count' : 'tyu'}}
    recipes = {0 : {'name' : 'Chicken', 'products' : products_dict, 'instructions' : 'this are the instructions'},
                    1 : {'name' : 'Beef', 'products' : products_dict_2, 'instructions' : 'this are the instructions for 2'}}

按钮创建:

            {% if recipes is not none%}
            {% for key, recipe in recipes.items() %}
            <button id={{key}} onclick="uploadRecipe({{recipe}})" type="button" class="btn btn-light btn-block">{{recipe['name']}}</button>
            {% endfor %}
            {% endif %}

和uploadRecipe函数

<script>
    function uploadRecipe(recipe) {
        products = recipe['products'];
        var table = document.getElementById("recipeProducts").getElementsByTagName('tbody')[0];
        $("#recipeProducts tbody tr").remove();
        for (var prop in products) {
            var row = table.insertRow(0);
            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);
            cell1.innerHTML = products[prop]['name'].bold();
            cell2.innerHTML = products[prop]['count'].bold();
        }
        document.getElementById("recipe_instructions_text").innerHTML = recipe['instructions'];
    }
</script>

推荐阅读