UFO ET IT

장고 템플릿의 변수 빼기

ufoet 2021. 1. 9. 10:38
반응형

장고 템플릿의 변수 빼기


쓸 수있다 {{ myval.add:5 }}, {{ myval|add:value }}심지어와 {{ myval|add:-5 }}.

그러나 값 * -1을 추가하기 위해 무엇을 입력해야하는지 알 수 없습니다 {{ myval|add:-value }}. 슬프게도 작동하지 않습니다.


내장 된 Django 템플릿 태그 / 필터는 모든 것을 포괄하지는 않지만 사용자 정의 템플릿 태그를 작성하는 것은 매우 쉽습니다 : https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

자신 만의 subtract템플릿 태그를 매우 쉽게 만들 수 있습니다.

@register.filter
def subtract(value, arg):
    return value - arg

큰 따옴표를 사용해야합니다.

{{ myval|add:"-5" }}

이것은에서 5를 뺍니다 myval.


https://pypi.python.org/pypi/django-mathfilters

install : $ pip 템플릿에 django-mathfilters 설치

{% load mathfilters %}

<ul>
    <li>8 + 3 = {{ 8|add:3 }}</li>

    <li>13 - 17 = {{ 13|sub:17 }}</li>

    {% with answer=42 %}
    <li>42 * 0.5 = {{ answer|mul:0.5 }}</li>
    {% endwith %}

    {% with numerator=12 denominator=3 %}
    <li>12 / 3 = {{ numerator|div:denominator }}</li>
    {% endwith %}

    <li>|-13| = {{ -13|abs }}</li>
</ul>

나는 최근에 Django로 작업을 시작했고 이것도 우연히 발견했습니다. n 번 후에 인쇄를 중지하고 나머지 항목을 토글하기 위해 "more"링크를 표시하는 매우 간단한 템플릿 루프가 필요했습니다.

큰 관심을 가지고 왜 이것이 Django 기본 필터에 추가되지 않는지 이해하려고 애쓰는 사람들의 투쟁을 읽었습니다 (2013 년 이전부터). 내가 문자열과 사용이 개 변수를 뺄 수있는 방법 사용자 지정 서식 태그를 만드는 것 같은 느낌과 내가 가지 발견되지 않았다 add과 결합을 with하고stringformat

예를 들어 처음 2 개를 인쇄하고 나머지는 숨기고 싶은 항목 목록이 있다고 가정 해 보겠습니다.

John, Anna 외 5 명이 좋아합니다 (7 개 항목의 목록이 제공된 경우).

보이는 항목의 수가 템플릿에 코드화되어있는 한 (예 : 2) 음수 2를 추가 할 수 |add:"-2"있지만 보이는 항목의 수도 변수가되기를 원했습니다. 위에서 제안한 Math-filter 라이브러리가 최신 상태가 아닌 것 같습니다 (Django 2.x로 테스트하지 않았습니다).

트릭은 add도우미 를 사용하여 문자열 "-"를 문자열로 정수와 연결하여 add도우미에 대한 연속 호출에서 음의 정수로 다시 강제 변환 될 수 있도록하는 것 같습니다 . 그러나 값이 문자열이 아닌 경우 작동하지 않으므로 stringformat도우미가 들어오는 곳입니다.

문자열 값으로

템플릿 posts.html(어떻게 visible명시 적으로 문자열로 전달 되는지 참고 -아래의 대안)

{% for post in posts %}
  <h4>{{ post.title }}</h4>
  ...
  {% include 'show_likes.html' with likes=post.likes visible="3" %}
{% endfor %}

template show_likes.html (note the add:0 to make the boolean operator work)

{% with show=visible|default:"2" %}
{% for like in likes %}
  {% if forloop.counter <= show|add:0 %}
    {% if not forloop.first %},{% endif %}
    {{ like.username }}
  {% endif %}
{% endfor %}
{% if likes|length > show|add:0 %}
{% with rest="-"|add:show %}
  and {{ likes|length|add:rest }} more
{% endwith %}
{% endif %}
like this
{% endwith %}

Alternative with integer

You could just convert your integer to a string in the calling template using |stringformat:"d"

If however the number of visible items you want to show is an integer, you'll have to add a call to stringformat:"d" to have it converted to string

template posts.html

{% for post in posts %}
  <h4>{{ post.title }}</h4>
  ...
  {% include 'show_likes.html' with likes=post.likes visible=3 %}
{% endfor %}

template show_likes.html

{% with show=visible|default:2 %}
{% with show_str=show|stringformat:"d" %}
{% for like in likes %}
  {% if forloop.counter <= show %}
    {% if not forloop.first %},{% endif %}
    {{ like.username }}
  {% endif %}
{% endfor %}
{% if likes|length > show|add:0 %}
{% with rest="-"|add:show_str %}
  and {{ likes|length|add:rest }} more
{% endwith %}
{% endif %}
{% endwith %}
{% endwith %}

Since I'm a very beginner with Django and Python, I'm pretty sure this approach is far worse than actually creating a custom helper! So I'm not suggesting anyone should be using this. This was just my attempt on trying to solve this with the available template helpers and without any custom stuff.

Hope this helps

ReferenceURL : https://stackoverflow.com/questions/9948095/variable-subtraction-in-django-templates

반응형