如何在用户开通Premium权限时禁用/销毁Bootstrap Modal弹窗
要实现当用户开通Premium权限(profile.premiumActive == true)时不再触发弹窗,我们可以从后端模板控制渲染和前端JS阻止触发两个层面入手,双重保障:
1. 后端模板修改:直接不渲染Premium用户的弹窗代码
这是最高效的方式,Premium用户的页面里根本不会加载弹窗的HTML结构,从根源避免弹窗出现。
修改你的Twig模板里的判断条件,在原有的if语句中添加and profile.premiumActive == false:
{% if profile is not null and profile.active == true and profile.premiumActive == false %} <div class="modal fade userprofile__activebs_modal" tabindex="-1" role="dialog" aria-labelledby="show_modal_label" aria-hidden="true"> <div class="modal-dialog" role="document" > <div class="modal-content"> <button type="button" class="close no-button" data-dismiss="modal" aria-label="Close"> </button> <div class="modal-title"> <h4 class="text-center"> {{ 'inactive_box.paragraph_3' | trans({}, 'user_profile') }} </h4> </div> </div> <div class="modal-body text-center"> <a class="link link--yellow link--underline2 mr-5" data-dismiss="modal" aria-label="Close"> <i class="fa-light fa-circle-x"></i> {{ 'buttons.no' | trans({},'forms') | raw | upper }} </a> <a class="link link--underline2 link--red2" href="{{ path('user_profile_third_step_premium',{ 'profileId':[profile.id.toString] }) }}"> <i class="fa-light fa-circle-check"></i> {{ 'buttons.yes' | trans({},'forms') | raw | upper }} </a> <div class="modal-footer"> </div> </div> </div> </div> {% endif %}
2. 前端JS修改:添加权限判断,阻止弹窗触发
为了防止极端情况(比如后端判断失效),我们在JS的点击事件里增加Premium权限判断,确保弹窗不会被意外触发。
步骤1:在页面中注入Premium状态
在HTML的<head>里添加一个隐藏的meta标签,用来存储用户的Premium状态:
<meta name="user-premium-status" content="{{ profile.premiumActive ? 'true' : 'false' }}">
步骤2:修改JS点击事件逻辑
在触发弹窗的代码前,先读取这个状态,如果是Premium用户,直接跳过弹窗逻辑:
$(document).on('click', '[data-activebs-message]', function (event) { // 获取用户Premium状态 const isPremium = $('meta[name="user-premium-status"]').attr('content') === 'true'; // 如果是Premium用户,直接放行,不触发弹窗 if (isPremium) { return; } event.stopPropagation(); event.preventDefault(); $('.userprofile__activebs_modal').modal().addClass('open'); }); // 其余原有的Modal关闭逻辑保持不变 $(document).on('hidden.bs.modal', '.userprofile__activebs_modal', function () { $('.userprofile__activebs_modal').removeClass('open'); }); $(document).on('hidden.bs.modal', '#show_modal', function (e) { $(this).parent().html(''); });
为什么这么做?
- 后端模板判断:减少页面冗余代码,提升加载速度,同时从根源上避免弹窗被渲染。
- 前端JS判断:作为兜底方案,防止后端逻辑出错导致弹窗意外出现,双重保障功能正常。
内容的提问来源于stack exchange,提问作者John Morrow
相关产品推荐
相关产品推荐

