python/Django
[Django] HTML Template 에서 지역변수 custom local variable 사용하기 - with 문
http://portfolio.wonpaper.net
2023. 5. 19. 12:41
Template code 상에서 임의의 지역변수를 사용하고자 할때 with 문을 넣어서 만들수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
{% with m_id=request.session.m_id %}
{% if m_id %}
<button type="button" class="btn btn-primary" onclick="location.href='/board/board_input'">글쓰기</button>
{% endif %}
{% if m_id == board.member_id %}
<button type="button" class="btn btn-primary" onclick="location.href='/board/board_mod/{{ board.b_no }}/'">수정하기</button>
<button type="button" class="btn btn-primary" onclick="boardDel({{ board.b_no }})">삭제하기</button>
{% endif %}
{% endwith %}
<button type="button" class="btn btn-primary" onclick="location.href='/board'">글목록</button>
|
cs |
위에서 with문으로 둘러치고 그안에 m_id 변수라고 세션변수값을 담는 지역변수를 하나 별도로 할당하였다.
https://pythoncircle.com/post/701/how-to-set-a-variable-in-django-template/
1
2
3
4
5
6
7
|
{% with business.employees.count as total %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
{% with var1="hello" var2="pythoncirlce" %}
{{ var1 }} {{var2}}
{% endwith %}
|
cs |
[ custom_template_tags.py ]
1
2
3
4
5
6
|
from django import template
register = template.Library()
@register.simple_tag
def setvar(val=None):
return val
|
cs |
[ HTML Template ]
1
2
3
4
5
6
7
8
9
|
{% load custom_template_tags %}
{% if is_login %}
{% setvar "Save" as action %}
{% else %}
{% setvar "Compile" as action %}
{% endif %}
Would you like to {{action}} this code?
|
cs |
참고 : https://pythoncircle.com/post/701/how-to-set-a-variable-in-django-template/
참고 : https://stackoverflow.com/questions/1070398/how-to-set-a-value-of-a-variable-inside-a-template-code
참고 : https://stackoverflow.com/questions/2697757/django-use-template-tag-and-with
참고 : https://stackoverflow.com/questions/8517933/django-assigning-variables-in-template
참고 : https://stackoverflow.com/questions/68654019/how-to-request-session-value-in-template-django