使用 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',  '10%', hide:true}
                    ,{field: 'a', title: 'a',  '5%', hide:true} 
                    , {fixed: 'right',  '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')
                }
            });
原文地址:https://www.cnblogs.com/lhly/p/13652270.html