3

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?

3
  • If you include a dynamic value, should that asset be static? You may have perfectly good reasons to do so, but it may hint poor application design aswell
    – Mischback
    Jul 31, 2015 at 22:01
  • 1
    @Mischback : I have images with file names that can be generated by the properties of the model objects. Instead of this, how do I approach the problem then.. Jul 31, 2015 at 22:06
  • Personally I would code my own template tag for this use-case: docs.djangoproject.com/en/1.8/howto/custom-template-tags
    – Mischback
    Jul 31, 2015 at 22:10

2 Answers 2

11

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

{% static SampleModel.0.propertyValue %} 
2
  • 2
    if the path is "images/{{ SampleModel.0.propertyValue }}.png" then? Aug 2, 2015 at 9:43
  • 3
    Then you can use the add filter: {% static "images"|add:SampleModel.0.propertyValue|add:".png" %}.
    – Alasdair
    Jan 4, 2018 at 18:45
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.