You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony 6中使用Sortable.js实现表格行拖拽排序报错求助

解决Symfony 6中Sortable.js "Sortable is not defined" 错误的方案

核心原因

Webpack Encore打包的JS模块默认处于局部作用域,你在app.js里导入的Sortable不会自动成为全局变量,所以视图里的独立脚本无法访问到它。


方案一:将Sortable暴露到全局(快速解决)

修改app.js的导入代码,把Sortable挂载到全局window对象上:

import Sortable from 'sortablejs';
window.Sortable = Sortable; // 让全局脚本能访问到Sortable

同时确保视图中的自定义脚本在app.js之后加载(比如在base.html.twig里先引入{{ encore_entry_script_tags('app') }},再写页面脚本)。


方案二:将初始化逻辑移到app.js(推荐,符合模块化规范)

删除视图里的独立<script>标签,把Sortable的初始化代码整合到app.js中,避免全局变量污染:

import Sortable from 'sortablejs';

// 等待DOM完全加载后执行初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化带手柄的表格行拖拽
    const listWithHandle = document.getElementById('listWithHandle');
    if (listWithHandle) {
        Sortable.create(listWithHandle, {
            handle: '.glyphicon-move',
            animation: 150
        });
    }

    // 若需要初始化simpleList,按同样逻辑处理
    const simpleList = document.getElementById('simpleList');
    if (simpleList) {
        Sortable.create(simpleList, { /* 你的配置项 */ });
    }
});

额外修复:表格HTML结构错误

你的表格行里有一个多余的嵌套<td>标签,会破坏表格结构,可能导致拖拽异常:
原错误代码:

<td class="pe-5"><td><a href="{{ path('delete_user_template', {id: userSample.id}) }}"><i class="fa fa-trash"></i></a></td>

修正为:

<td class="pe-5"><a href="{{ path('delete_user_template', {id: userSample.id}) }}"><i class="fa fa-trash"></i></a></td>

内容的提问来源于stack exchange,提问作者mardon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 09:42:32