테스트를 위해 view를 만든다.app/views.py 에 테스트 뷰를 만든다.
class TestView(TemplateView):
template_name = test.html'
context = [ {'IP ADDRESS': '192.168.100.1', 'HOSTNAME': 'Fox', 'Connect': 'ssh'},
{'IP ADDRESS': '192.168.100.2', 'HOSTNAME': 'Wolf', 'Connect': 'telnet'},
{'IP ADDRESS': '192.168.100.3', 'HOSTNAME': 'Hotdog', 'Connect': 'ssh'},
]
def get(self, request):
return render(request, self.template_name, {'context': self.context})
app/urls.py 에 path를 등록한다.
urlpatterns = [
path('test/', TestView.as_view(), name='test'),
]
템플릿을 만든다. templates/app/test.html
{% block content %}
<table>
<tr>
<td>IP</td><td>Hostname</td><td>Connect</td>
</tr>
{% for i in context %}
<tr>
{% for key, value in i.items %}
<td>
{{ value }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
{% endblock content %}
여기까지 하면 모든 content를 템플릿을 통해 표시 할 수는 있지만, 원하는 값을 원하는 위치에 표시하는것은 쉽지 않다.
이제, 이 문제를 해결하기위해 custom template tag를 만든다.app/templatetags 디렉토리를 생성한다.
__init__.py 생성하고, custom_filters.py 를 만든 후 아래 내용을 넣는다. 그리고, 반드시, 서버를 다시 시작해야 한다(manage.py runserver). 다시 시작하지 않으면 적용되지 않는다.
from django import template
register = template.Library()
@register.filter('reportkey')
def reportkey(dict_data, key):
if key in dict_data:
return dict_data.get(key)
이제, 템플릿을 수정한다. custom template tags를 load하고, {{ dict | custom_filter_func:”key” }} 형식으로 데이타를 지정하면 된다.
emplates/app/test.html
{% load custom_filters %}
{% block content %}
<p>Test ...</p>
{% for c in context %}
<table>
<tr>
<td>IP Address</td>
<td>Hostname</td>
</tr>
<tr>
<td>{{ c | reportkey:"IP ADDRESS" }}</td>
<td>{{ c | reportkey:"HOSTNAME" }}</td>
</tr>
<tr>
<td>Connect</td>
<td>
{{ c | reportkey:"Connect" }}
</td>
</tr>
</table>
<p>
<hr>
</p>
{% endfor %}
{% endblock %}