我是Django的新手,我需要一些导航栏项目才能在新标签页中打开。我的问题是target =“ _ blank”无法正常工作。我检查了if逻辑是否有效。
这是模板中的代码
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
{% for navName, navUrl, openInNewTab in navItemsList %}
{% if navItemsList == True %}
<li class="nav-item active">
<a class="nav-link" href="{{ navUrl }}" target="_blank"> {{ navName }} <span class="sr-only">(current)</span></a>
</li>
{% else %}
<li class="nav-item active">
<a class="nav-link" href="{{ navUrl }}"> {{ navName }} <span class="sr-only">(current)</span></a>
</li>
{% endif %}
{% endfor %}
</ul>
</div>
这是查看中的代码
from django.http import HttpResponse
from django.shortcuts import render
from navbarItems.models import navItems
def home_page(request):
#Navigation items
linkNames = [entry.linkName for entry in navItems.objects.all()]
urls = [entry.url for entry in navItems.objects.all()]
openInNewTab = [entry.openNewTab for entry in navItems.objects.all()]
navigationItemList = list(zip(linkNames, urls, openInNewTab))
context = {"header_title" : 'Hidden Dimsum',
"body_title" : 'Here is the title for the webpage',
"navItemsList" : navigationItemList}
return render(request, template_name = 'base.html', context = context)
在navbarItems.models中,我有以下代码
from django.db import models
# Create your models here.
class navItems(models.Model):
linkName = models.TextField(null = False, blank = False)
url = models.TextField(null = False, blank= False)
openNewTab = models.BooleanField(default=False, blank=False)
答案 0 :(得分:1)
您可以执行以下操作:
views.py:
from navbarItems.models import navItems
def home_page(request):
#Navigation items
navigationItemList = navItems.objects.all()
context = {
"header_title": 'Hidden Dimsum',
"body_title": 'Here is the title for the webpage',
"navItemsList": navigationItemList
}
return render(request, template_name='base.html', context=context)
模板:
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
{% for nav_item in navItemsList %}
<li class="nav-item active">
<a class="nav-link" href="{{ nav_item.url }}" {% if nav_item.openNewTab %} target="_blank"> {% endif %} {{ nav_item.linkName }} <span class="sr-only">(current)</span></a>
</li>
{% endfor %}
</ul>
</div>
</nav>