Concatenate integer and string in a Djangoplate theme

1

Good morning,

The problem I have is that I want to concatenate an int with a string in a Django template, but when I try it, I return an empty value. This is my code:

{% with "object_"|add:obj.id as check_id %}
El objeto es {{check_id}}
{% endwith %}

Apparently this code does not work because obj.id is an integer and "object_" is a string. I would like to know what is the correct way to add an integer to a string within the template.

I clarify that obj , is an object that happened from the view and when I show only that value, if I get the id in the following way:

{{obj.id}}

Thanks in advance.

    
asked by Nazkter 06.03.2017 в 23:21
source

1 answer

1

It does not work because the filter add converts (or tries to convert ) both values to numbers. Fail because you can not do it with "object_" .

You have several alternatives:

Alternative 1. Presentation only.

If you want to join the string, just for presentation purposes, then you do not need any logic, just use the value next to the string.

{# Alternativa 1 #}
El objeto es object_{{ obj.id }}

Alternative 2. Parameter in a URL

If you want to use the value as a parameter of a URL to pass it to a function, you can dispense with the text and use only the number:

# En urls.py
(r'^(?P<check_id>\d+)$', 'check_id_view')

{# en una plantilla #}
<a href="{% url 'check_id_view' check_id=obj.id %}">object_{{ obj.id }}</a>

Alternative 3. A filter

You can avoid placing business logic in the template using a custom filter (see the documentation ).

# En templatetags/filtros.py
from django import template


register = template.Library()

@register.filter(name='check')
def check(id):
    try: return "object_%d" % id
    except KeyError: return ""

and it is used like any other filter

{# Alternativa 3 #}
El objeto es {{ obj.id|check }}
  

I have not tried the code, but it gives you an idea of what you can do.

    
answered by 07.03.2017 / 00:32
source