标签:
你可能已经注意到我们在例子视图中返回文本的方式有点特别。 也就是说,HTML被直接硬编码在 Python 代码之中。
下面我们来调用html
views
def index(request,user): if request.method == ‘GET‘: user_info = { ‘username‘:‘alex‘, ‘name‘:‘Alex Li‘ } return render(request,‘app01/index.html‘,{‘user_obj‘:user_info}) else: return HttpResponse("transfered 10000 to ")
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Payment</title> </head> <body> <h1>Welcome to Oldboy shopping</h1> <h2>username: {{ user_obj.username }}</h2> <h2>name: {{ user_obj.name }}</h2> </body> </html>
项目urls
urlpatterns = [ url(r‘^$‘,views.index), url(r‘cash/$‘,views.pay_by_cash), ]
总项目urls
urlpatterns = [ url(r‘^admin/‘, include(admin.site.urls)), url(r‘^payment/‘,include(payment_urls),{‘user‘:‘alex‘}) ]
访问 http://127.0.0.1/payment
Django 模板渲染
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Payment</title> </head> <body> <h1>Welcome to Oldboy shopping</h1> <ul> {% for user_obj in user_objs %} {% if user_obj.username == ‘alex3‘ %} <li style="background-color: chartreuse">username:{{ user_obj.username }},name:{{ user_obj.name }}</li> {% else %} <li>username:{{ user_obj.username }},name:{{ user_obj.name }}</li> {% endif %} {% endfor %} </ul> </body> </html>
views
def index(request,user): if request.method == ‘GET‘: user_infos = [ {‘username‘:‘alex‘,‘name‘:‘AlexLi‘}, {‘username‘:‘alex2‘,‘name‘:‘AlexLi2‘}, {‘username‘:‘alex3‘,‘name‘:‘AlexLi3‘}, {‘username‘:‘alex4‘,‘name‘:‘AlexLi4‘} ] # print("user request:",request.GET.get(‘user‘)) return render(request,‘app01/index.html‘,{‘user_objs‘:user_infos}) # return HttpResponse("welcome to payment index.......%s" %user) else: return HttpResponse("transfered 10000 to ")
设置从哪一行开始
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Payment</title> </head> <body> <h1>Welcome to Oldboy shopping</h1> <ul> {% for user_obj in user_objs %} {% if forloop.counter0 > 2 %} <li style="background-color: chartreuse">username:{{ user_obj.username }},name:{{ user_obj.name }}</li> {% else %} <li>username:{{ user_obj.username }},name:{{ user_obj.name }}</li> {% endif %} {% endfor %} </ul> </body> </html>
被2整除
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Payment</title> </head> <body> <h1>Welcome to Oldboy shopping</h1> <ul> {% for user_obj in user_objs %} {% if forloop.counter0|divisibleby:"2" %} <li style="background-color: chartreuse">username:{{ user_obj.username }},name:{{ user_obj.name }}</li> {% else %} <li>username:{{ user_obj.username }},name:{{ user_obj.name }}</li> {% endif %} {% endfor %} </ul> </body> </html>
标签:
原文地址:http://www.cnblogs.com/yexiaochong/p/5738420.html