使用Jinjia模板语法将数据传递给JavaScript变量

网上很容易查到jinjia循环加载后端传来的数据到页面上的方法,但是很难搜到怎么通过jinjia获取flask后端传过来的数据给java script的变量赋值,特此记录。

先来看一下我们传输的数据:

@test_bp.route('/test')
def test():
    role = "admin"
    permission = ["r1","r2","r3"]
    project = [
            ["project","project","project","non-project","non-project"],
            ["p1","p2","p3","tool","other"]
        ]
    action= {
        "p1":["a1","a2","a3"],
        "p2":["b1"],
        "p3":["c1","c2"],
        "tool":["design","development"],
        "other":["please specify"]
            }


    return render_template('test.html', action=action,project=project,role=role,premission=permission)

【方法一】:最初找到的方法,非常复杂,根据传来的数据的结构通过Jinjia不断循环

  <script>
        // 在js里先建好空数据
        let role = ""
        let permission = []
        let sourceAllProjects = []
        let sourceAllActions = {}
    </script>


    <!--把jinjia2的变量赋值到js的变量-->
    <!--    传一个字符串变量-->
    <script type="text/javascript">
        role = '{{role}}' //记得这里有引号
    </script>

    <!--    传一个列表变量-->
    {% for p in permission %}
        <script type="text/javascript">
            permission.push('{{p}}');
        </script>
    {% endfor %}


    <!--    传一个列表套列表-->
   {% for p in project %}
        <script type="text/javascript">
            temp = ["",]
        </script>
        {% for pp in p %}
        <script type="text/javascript">
            temp.push('{{pp}}');
        </script>
    {% endfor %}
        <script type="text/javascript">
            sourceAllProjects.push(temp);
        </script>
    {% endfor %}


    <!--    传一个字典套列表-->
    {% for k,v_list in action.items() %}
        <script type="text/javascript">
            temp = [""]
        </script>
        {% for v in v_list %}
            <script type="text/javascript">
                temp.push('{{v}}')
            </script>
        {% endfor %}
        <script type="text/javascript">
            sourceAllActions["{{ k }}"] = temp
        </script>
    {% endfor %}



<script>
    $(document).ready(function() {
        console.log(role)
        console.log(permission)
        console.log(sourceAllProjects)
        console.log(sourceAllActions)
    })
</script>

最后的结果:

 【方法二】:我真的栓Q,其实这样就好了

<script>
  var action = {{ action | tojson }};
  var project = {{ project | tojson }};
  var role = "{{ role }}"; //记得这里要用引号!
  var permission = {{ permission | tojson }};
$(document).ready(function() {
    console.log(role)
    console.log(permission)
    console.log(project)
    console.log(action)
})
</script>

 欲哭无泪,第一种方法用了很久..写得我眼睛都瞎了

csdn上没有搜到过详述这种方法的,特此记录