Danna Capellan
Danna Capellan

Reputation: 127

When I include a template in another template how can I pass the path of a source file?

I have two templates that go together, one inside the other. The inner one has an icon that needs to change according to the content of the parent template.

I've tried to pass the icon path using a variable:

src="{% url 'main_bar_icon' %}"> 

and I added this line of code in the parent template:

{% with main_bar_icon='../static/dist/img/logout-icon.svg' %}
{% include 'main_bar.html' %}
{% endwith %}

So, this is my inner template:

{% block main_bar %}
    <a href="">
        <img class="app-main-bar-icon" 
             src="{% url 'main_bar_icon' %}">
    </a>
{% endblock main_bar %}

And this is my parent template:

{% block content %}
    {% with main_bar_icon='/dist/img/logout-icon.svg' %}
    {% include 'main_bar.html' %}
    {% endwith %}
{% endblock content%}

In the browser I get this:

<img class="app-main-bar-icon" src(unknown) alt="icon">

Upvotes: 0

Views: 31

Answers (1)

mfrackowiak
mfrackowiak

Reputation: 1304

Unfortunately, the {% url ... %} templatetag, can be only used to retrieve urls for the views defined in the urlpatterns.

For your needs, you will need either:

  • use plain variable, since you already assign path to the variable, simply: <img class="app-main-bar-icon" src="{{ main_bar_icon }}">

  • or, for more future proof solution, you can configure django static files and use {% with main_bar_icon='dist/img/logout-icon.svg' %} and then <img class="app-main-bar-icon" src="{% static main_bar_icon %}">

Upvotes: 1

Related Questions