我是Django的新手。我试图将一个字典传递给我的模板视图页面,但是当我尝试使用for循环打印字典值时,它不会打印。
-mytest
-personal
-templates
-personal
-includes
-basic.html
-header.html
-home.html
-urls.py
-views.py
-webapp
view.py
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'personal/home.html')
def contact(request):
return render(request,'personal/basic.html',{'contents':['if you like to contact me, please email me','ansarijuned@gmail.com']})
basic.html
{% extends "personal/header.html" %}
{% block content %}
<p>This is My Home page with Header</p>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h2>Contact Us</h2>
<hr />
<% for obj in contents %>
<p>{{ obj }}</p>
<% endfor %>
</div>
</div>
</div>
{% include "personal/includes/headerwidget.html" %}
{% endblock %}
urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^contact/', views.contact, name='contact'),
]
答案 0 :(得分:3)
在模板中,您尝试访问不存在的{{c}}
对象。您的数据位于{{obj}}
,您可以通过以下方式访问:
{% for obj in contents %}
{{ obj }}
{% endfor %}
然后,如果您想测试obj
是否等于hi
,您可以这样做:
{% for obj in contents %}
{% if obj == "hi" %}
{{ obj }}
{% endif %}
{% endfor %}
答案 1 :(得分:0)
替换您的模板
<% for obj in contents %>
<p>{{ c }}</p>
<% if(obj== 'hi') %>
{{c}}
<% endif %>
<% endfor %>
带
<% for obj in contents %>
<p>{{ obj }}</p>
<% if(obj== 'hi') %>
{{obj}}
<% endif %>
<% endfor %>
然后你会得到你在字典中传递的内容。