Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django template compare templatetag result with variable?

I’ve got template tag, that returns selected (earlier) location name of the store:


@register.simple_tag( takes_context=True)
def getSelectedLocation(context):
    request = context['request']
    locationId = request.session.get('locationId') 
    if (locationId):
        location = Location.objects.get(id = locationId)
    else:
        location = Location.objects.first()
    return location.locationName

and in my template I’d like to compare it with actual variables:

 {%for eq in obj.equipment.all %} 
                
 {%if getSelectedLocation != 'eq.storageLocation.locationName' %}
 something 
 {%endif%}
 {%endfor%}
 

(in general, template tag works ok, ie/ if called like {% getSelectedLocation %} returns correct name). But comparison won’t work.
Is it possible to do it that way? I think I can’t move that logic to a view, as it enumerates over obj object foreign key values…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any suggestions?

>Solution :

That makes sense, since here it will not evaluate the template tag, it will just look for a variable named getSelectedLocation, and there is no such thing, hence the problem.

You can store the result in a variable, like:

{% getSelectedLocation as selectedLocation %}
{%for eq in obj.equipment.all %} 
    {%if selectedLocation != 'eq.storageLocation.locationName' %}
        something 
    {%endif%}
{%endfor%}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading