Press "Enter" to skip to content

Tag: django

Django parse a json/dictionary reminder on template

如果想在一个Django template里引入json, 正确的template写法为

python的views.py的写法

# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import Http404, HttpResponse

def get_product(request):
context1 = {}
context1[‘env’] = ‘production’
context1[‘mydict’] = {"key1":"value1", "key2":"value2", "key3":"value3", "key4":"value4"}
context1[‘days’] = [1,2,3]

if request.GET.get("item") == "ec2" or not request.GET.get("item"):
return render(request, ‘main_content.html’, context1)
else:
raise Http404()

main_content.html使用extends引入index.html

{% extends 'index.html' %}
{% block content %}
{% for day in days %}
<li>day: {{ day }}</li>
{% endfor %}
{% endblock %}

index.html使用include引入sidebar.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="header">My page</div>
<div class="content">
<div class="sidebar">

<ul>
{% if env == 'production' %}
{% include 'production.sidebar.html' %}
{% elif env == 'development %}
{% include 'development.sidebar.html' %}
{% elif env == 'staging' %}
{% include 'staging.sidebar.html' %}
{% elif env == 'legacy' %}
{% include 'legacy.sidebar.html' %}
{% endif %}
</ul>

</div>
<div class="maincontent">

{% block content %} {% endblock %}

</div>
</div>
</body>
</html>
Leave a Comment