我有模板标签,它返回商店的选定(较早)位置名称:
@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
在我的模板中,我想将其与实际变量进行比较:
{%for eq in obj.equipment.all %}
{%if getSelectedLocation != 'eq.storageLocation.locationName' %}
something
{%endif%}
{%endfor%}
(一般来说,模板标签工作正常,即/如果像 {% getSelectedLocation %} 那样调用则返回正确的名称)。但比较是行不通的。 可以这样做吗?我认为我无法将该逻辑移至视图,因为它枚举了 obj 对象外键值...
有什么建议吗?
这是有道理的,因为这里它不会评估模板标签,它只会查找名为
getSelectedLocation
的变量,而没有这样的东西,因此出现了问题。
您可以将结果存储在变量中,例如:
{% getSelectedLocation as selectedLocation %}
{%for eq in obj.equipment.all %}
{%if selectedLocation != 'eq.storageLocation.locationName' %}
something
{%endif%}
{%endfor%}