I'm really new in JavaScript and I have a question: I need to add inside an inner Html, a Django template if statement that uses a JavaScript variable to compare (in this case the variable is event_id)
I have tried a lot of alternatives after hours and also I have searched with no success.
This is my JS code.
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 %}
`;
}
with this option, I'm getting this error:
Could not parse the remainder: '${event_id}' from '${event_id}'
and if I change it for {% if reservation.id ==
+ event_id + %}
, I'm getting this error: Could not parse the remainder: '
' from ''
So, is that possible to do? Do you know how could it work please !!! I really don't know how to solve it, I really appreciate your help thanks :)
Something like this could work for you:
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
}
First of all you create a new javascript variable (called reservations
), then you concatenate the desired <option>
string into another variable (innerHtml
). Finally you set the innerHtml
to your selected_group_member
.
Update
Added | safe
template tag https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#safe as discovered in comments.