4

I have two variables var1 and var2. I want to do this,

{% blocktrans %}
    value of my var is: {% firstof var1 var2 %}
{% endblocktrans%}

It gives me error that 'blocktrans' doesn't allow other block tags. Because we are not allowed to use any other tag inside blocktrans, what is the solution of this kind of problem?

Tasawer Nawaz
  • 927
  • 8
  • 19

2 Answers2

7

From django 1.9 onwards, you can use firstof to assign result to context.

{% firstof var1 var2 as myvar %}

{% blocktrans %}
    value of my var is: {{ myvar }}
{% endblocktrans%}

See django-docs and issue tracker for reference.

v1k45
  • 8,070
  • 2
  • 30
  • 38
0

I can't use the partner's answer because I use django version < 1.9, for me the solution was the one found in the following link (don't forget to like Shang Wang if it worked for you): Put the result of simple tag into a variable

As our friend Shang says, you must create a method with the assignment_tag decorator, this way we can save the response in a method and consume it from the template:

@register.assignment_tag(takes_context=True)
def precio_format_with_locale_assignment(context, cantidad):
    locale = context.dicts[1]["locale"]
    reserva = context.dicts[1]["reserva"]
    return format_price_with_locale(reserva, cantidad, locale)

As you can see I added (takes_context=True) to access to the context as in a simple_tag.

And to use it in the template:

{% precio_format_with_locale_assignment interval.amount as interval_amount %}

{% blocktrans with date=interval.date trimmed %}
     Desde el {{ date }}: se cobrarĂ¡n {{ interval_amount }}.
{% endblocktrans %}
                                                                       
IvanAllue
  • 434
  • 3
  • 11