장고 템플릿에 날짜를 표시하고 있습니다. 오늘 날 날짜 형식을 지정하고 템플릿에 전달하는 파이썬 함수가 있습니다.Django 템플릿 태그 나 파이썬에서 변수를 전달하는 것이 더 낫습니다.
# function [format example: Wednesday 01 February 10:00:00]
def today():
date_now = datetime.now()
day_number = date_now.strftime("%d")
month_name = date_now.strftime("%B")
day_name = date_now.strftime("%A")
time = date_now.strftime("%X")
date = "{} {} {} {}".format(day_name, day_number, month_name, time)
return date
# view
def myview(request):
the_date_today = today()
context = {
"the_date_today": the_date_today,
}
return render(request, "template.html", context)
# template
<h1>{{ the_date_today }}</h1>
방금 장고 템플릿 태그를 사용하여이 작업을 수행했습니다.
# view
def myview(request):
the_date_today = datetime.now()
context = {
"the_date_today": the_date_today,
}
return render(request, "template.html", context)
# template
<h1>{{ the_date_today|date:"l m F H:i" }}</h1>
어떻게하면 더 좋은 방법일까요? 템플릿 필터를 사용하는 코드가 훨씬 적지 만 느려지는 것은 무엇입니까?
템플릿 필터는 어떤 느린 당신의 응용 프로그램을 만들 수 없습니다 : 템플릿에
now
를 호출 할 수 있기 때문에은 무엇보다, 당신도 템플릿에
the_date_today
에 대한 값을 통과 할 필요가 없습니다. 그 뒤에는 파이썬 함수가 있습니다. 템플릿에서 프리젠 테이션을 유지하는 것이 가장 좋습니다. 표준 Django 템플릿 필터를 사용하는 것이 좋습니다. – dentemm