Home > database >  concatenate in django template
concatenate in django template

Time:04-05

Why does in this snippet id="{{field_index}}" is empty, it doesn't print me "field_version_" or "field_controparte" depending of key?

 <form id="formDoc" style="margin-top: 10px;" action="/" method="post">
        {% for keyFi,valueFi in tmplVar.jsonKeysDocFields.items %}
            
        {% with field_index="field_"|add:keyFi|stringformat:"s" %}
    
            <div style="margin-bottom: 5px; display: none;" id="{{field_index}}" 

CodePudding user response:

According to the documentation of the add template filter:

This filter will first try to coerce both values to integers. If this fails, it’ll attempt to add the values together anyway. This will work on some data types (strings, list, etc.) and fail on others. If it fails, the result will be an empty string.

I am guessing that your keyFi variable is None or some other type. Try debugging and checking for what value does that variable take.

CodePudding user response:

I tried also build a custom tag

file pyconcat_tags.py

from django import template
register = template.Library()
@register.filter
def concat_string(value_1, value_2):
    return str(value_1)   str(value_2)

file home.html

{% load pyconcat_tags %}
    <form id="formDoc" style="margin-top: 10px;" action="process2_module_doc.php" method="post">
        {% for keyFi,valueFi in tmplVar.jsonKeysDocFields.items %}
            
        {% with field_index="field_"|concat_string:keyFi %}
        <div style="margin-bottom: 5px; display: none;" id="{{field_index}}" >

Output me field_0, field_1 depending keyFi={"0":"version","1":"controparte"}

It works.

  • Related