1. 程式人生 > 實用技巧 >使用 django 和 layui,TemplateSyntaxError 錯誤 {{# }}

使用 django 和 layui,TemplateSyntaxError 錯誤 {{# }}

  1. 報錯
    使用 django 和 layui 寫後臺網站時,在 table.render({ })中使用 switch 開關,出現如下錯誤:
    django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: ‘# if(1){’ from ‘# if(1){’
    django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: ’ == 10006 ? ‘checked’ : ‘’’ from ‘d.id == 10006 ? ‘checked’ : ‘’’

  2. 分析:
    最終原因是 django 自動識別 {{ }} 為模板的變數程式碼:

    {{ 變數 }}:變數程式碼
    {% 程式碼段落 %}:邏輯程式碼

   而 {{# if(false)}} 是 js 的邏輯程式碼,被django 誤讀

3. 解決方案

   使用{% verbatim %}…{% endverbatim %} 標記即可

4. 案例

表格資訊:

<script>
        layui.use(['form', 'layedit', 'laydate', 'element', 'jquery', 'table'], function () {
            var form 
= layui.form, layer = layui.layer, element = layui.element, table = layui.table, $ = layui.jquery; var dbTab = table.render({ elem: '#xxx' , height: 1012 , url: '/xxx/xxx/' , method:
'post', where: { a: '{{ a}}', b: '{{ b }}' }, contentType: 'application/x-www-form-urlencoded' , page: false , cols: [[ //表頭 {field: 'id', title: 'id', width: '10%', hide:true} ,{field: 'a', title: 'a', width: '5%', hide:true} , {fixed: 'right', width: '20%', align: 'center', title: '操作', toolbar: '#barDemo'} //這裡的toolbar值是模板元素的選擇器 ]] }); </script>

繫結工具條:

<script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" lay-event="app">a/a>
        {% verbatim %}{{#  if(d.app_status=="失敗"){ }}
          <a class="layui-btn layui-btn-xs" lay-event="b">b</a>
        {{#  } }}
{% endverbatim %}
</script>

工具條操作

  table.on('tool(test)', function (obj) {
                var data = obj.data; //獲得當前行資料
                var layEvent = obj.event;

                if (layEvent === 'a') {
                    layer.msg('開始...',{
                        icon:16,
                        time:-1
                    });
                     miontApp(obj, data)
                }else if (layEvent === 'b'){
                    app_modify('/xxx/xxx_update/', data)
                }else{
                    layer.alert('error')
                }
            });