如何将Twig中的数据传递给JS脚本,在模态框展示Board的名称与描述
解决方法
你不需要提前定义全局的Twig兼容变量,每个Board(Bar实体)的数据不同,直接将对应数据绑定到触发按钮的自定义属性上,点击时动态读取即可。
步骤1:修改Twig标签页按钮代码
给循环生成的按钮新增data-*自定义属性存储对应Bar的名称和描述,同时做转义处理避免特殊字符破坏HTML结构:
<div class="tab-pane fade" id="pills-boards" role="tabpanel" aria-labelledby="pills-boards-tab"> <p> {% for bar in foo.bars %} <p> <button type="button" class="alert_demo_2 btn btn-secondary" data-bar-name="{{ bar.name|e('html_attr') }}" data-bar-description="{{ bar.description|default('')|e('html_attr') }}"> {{ bar }} </button> </p> {% endfor %} </p> </div>
e('html_attr')用于转义特殊字符,避免属性值内的引号、尖括号破坏HTML结构default('')处理描述字段为空的场景,避免渲染报错
步骤2:修改JS逻辑
移除原来的全局变量定义,点击按钮时动态读取当前按钮绑定的自定义属性:
<script> //== Class definition var SweetAlert2Demo = function() { //== Demo var initDemos = function() { //== Sweetalert Demo 2 $('.alert_demo_2').click(function(e) { const barname = $(this).data('bar-name'); const bardescription = $(this).data('bar-description'); swal(barname, bardescription, { buttons: { confirm: { className : 'btn btn-success' } } }); }); } return { //== Init init: function() { initDemos(); } }; }(); //== Class Initialization jQuery(document).ready(function() { SweetAlert2Demo.init(); }); </script>
注:原JS代码缺少initDemos函数的闭合大括号,上述代码已补全
注意事项
你提供的dump输出显示当前Folder(Foo实体)的关联Board集合为空,测试前请先给该实体绑定对应的Bar数据,否则循环不会生成按钮。
内容的提问来源于stack exchange,提问作者Paquito Uman
相关产品推荐
相关产品推荐

