I have a web app, frontend using normal HTML5, backend using Django.
In the frontend page, I have a JavaScript template literal function. Which is supposed to render all the individual value into a selection box of a queryset passed from backend to a bootstrap table.
view.py:
def view_material(request):
query_results_publisher = Publisher.objects.all()
return render(request, 'material/index.html', context={'Publisher':query_results_publisher})
publisher is query set: <QuerySet [<Publisher: >, <Publisher: Arkib Negara Malaysia>, <Publisher: DBP>, <Publisher: Edward Elgar>...]
index.html(bootstrap table + javascript template literal function):
...
<th class ='publisher' data-field="book.publisher" data-formatter="renderPublisher">Publisher</th>...
<script>
var Publisher = "{{ Publisher }}";
var publisher = '';
function renderPublisher(value) {
return `select style="width: 7em" name="" id="">
for (publisher in ${Publisher}) {
<option value="eText" ${(value === 'eText') ? 'selected="selected"' : ""}>
publisher</option>}</select>}`
</script>
But my for loop in javascript template literal function is not working, seems like I have some problem with the template literal usage in for loop.
How to correct my function?
You need check value of Publisher before loop it, if it is array, use for-of, if is object, use for-in. But in your case, I saw you print publisher, not it property, so i guest it must be array ( change if im wrong ) . Something like :
var publishers = "{{ Publisher }}"; // no capital for variable' name
function renderPublisher(value) {
var renderString = 'select style="width: 7em" name="" id=""'
for (publisher of publishers) {
renderString += `
<option value="eText" ${value === 'eText' ? "selected" : ""}> ${publisher}</option>`
}
renderString += '</select>'
return renderString;
}