Django use a variable within a template tag

感情迁移 提交于 2020-01-11 13:05:25

问题


I am using the static template tag in my Django template:

{% load staticfiles %}
<img src="{% static "my_app/myexample.jpg" %}" alt="My image"/>

But instead of "my_app/myexample.jpg", I need to use a file name that is a property of my model object (i.e. {{ SampleModel.0.propertyValue }}, which I am passing as context to this template. But how do I include {{ ... }} within the static template tag? It throws an error.

Any way out?


回答1:


You can use use a variable in the static template tag. Note that you don't need the {{ or }}

{% static SampleModel.0.propertyValue %} 



回答2:


You can use any variable from your context in Django tags (custom tags may need some adjustments to work with it). In your case, this works fine:

{% static SampleModel.0.propertyValue %} 

This usages also work:

{% with my_computed_var=SampleModel.0.propertyValue %}
    {% static my_computed_var %} 
{% endwith %}

{% static some_var|customFilter %}

See the documentation about custom tags for more information, it is also relevant for Django defaults tags.



来源:https://stackoverflow.com/questions/31755765/django-use-a-variable-within-a-template-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!