内部 HTML with Django Template If Statement Use Js Variable

Inner HTML with Django tamplate if statement usig Js variable

我是 JavaScript 的新手,我有一个问题: 我需要在内部 Html 中添加一个 Django 模板 if 语句,该语句使用 JavaScript 变量进行比较(在本例中变量为 event_id)

下班后我尝试了很多替代方案,但我也没有成功搜索。

这是我的JS代码。

eventClick: function (info) {
                var event_id = info.event.id;
                 $('#exampleModalToggle').modal('show');
                selected_group_member.innerHTML = `
                {% for reservation in reservations_api %}
                {% if reservation.id == ${event_id} %}
                <option value="1" selected>{{reservation.id}}</option>
                {% endif %}
                {% endfor %}
                `;
                }

使用此选项时,我收到此错误: Could not parse the remainder: '${event_id}' from '${event_id}'

如果我将其更改为 {% if reservation.id == + event_id + %},我会收到此错误:Could not parse the remainder: '' from ''

那么,这可能吗?你知道它是怎么工作的吗!!! 我真的不知道如何解决它,我真的很感谢你的帮助 谢谢:)

类似这样的东西对你有用:

eventClick: function (info) {
  const reservations = '{{ reservations_api | safe }}';
  var event_id = info.event.id;
  $('#exampleModalToggle').modal('show');

  let innerHtml = '';
  reservations.forEach((reservation) => {
    if (reservation.id == event_id)
      innerHtml += `<option value="1" selected>${reservation.id}</option>`;
  });

  selected_group_member.innerHTML = innerHtml
}

首先创建一个新的 javascript 变量(称为 reservations),然后将所需的 <option> 字符串连接到另一个变量(innerHtml)中。最后,您将 innerHtml 设置为您的 selected_group_member

更新

已添加 | safe 模板标签 https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#safe,如评论中所述。