实际上,如果您将 Bootstrap5 与 Django 一起使用,那么他们将内容作为字符串传递的方法是完美的,并且符合 Django 的模板包含。您可以使用您需要的任何部分 HTML 创建一个模板文件,例如,对于 Bootstrap5 似乎没有 X-editable 似乎可以工作,所以您可能希望与 Ok|Cancel 按钮一起进行行编辑作为内容.无论如何,这就是我的意思:
<button data-bs-content="{% include './popover_content.html' %}" type="button" class="btn btn-lg btn-danger" data-bs-toggle="popover" title="Popover title" >
Click to toggle popover
</button>
我的settings.py 模板部分如下所示:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True, # True is necessary for django-bootstrap5 to work!
'OPTIONS': {
'debug': True,
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
我将(每个应用程序的)模板保存在 <project dir>/templates/<app name> 文件夹中。我在MyMainApp/home.html 旁边有MyMainApp/popover_content.html,上面的示例代码已经过测试。但是,如果您将模板保存在每个应用程序的 Django 文件夹中,那么您需要将“MyApp/templates”添加到 TEMPLATES[0]{'DIRS': ['MyApp/templates', 'MyApp2/templates']} 列表中。
因此,至少这将使您能够将弹出框 HTML 置于通常的、语法高亮的 Django 模板格式中,并充分利用 Django 模板模块化成组件。
我个人打算用它来制作一个可编辑的标签(我的应用中一些数据的标题和描述字段)。
一个缺点是,如果您在包含以下内容时使用双引号 ("):"{% include './popover_content.html' %}", then you must use single quotes all throughout the popover_content.html` 模板。
您还需要为弹出框启用 html,因此您的站点范围的弹出框初始化程序会:
<script type="text/javascript">
$(document).ready(() => {
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(
function (popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl, {
html: true,
});
});
});
</script>
这是(未设置样式的)结果。总之,使用默认提供的字符串传入方法,并传入一个包含的Django模板文件。问题解决了!